[rspec-users] Is it possible to access Example scope from Formatter?

Jarmo Pertman jarmo.p at gmail.com
Mon Oct 19 15:50:51 EDT 2009


Thank you for the reply!

I have to admit that for a second I thought about using 'options'
somehow, but wasn't sure if it would work or not so i forgot the
possibility to use it at all and tried different approaches.

Anyway, it seems that your exact code snippet doesn't work so I made
one formatter and spec to see what happens. Formatter is written like
this:
require 'spec/runner/formatter/base_text_formatter'

class OptionsFormatter < Spec::Runner::Formatter::BaseTextFormatter

  def example_group_started(example_group_proxy)
    puts "example_group_started"
    p example_group_proxy.options
    super
  end

  def example_started(example_proxy)
    puts "example_started"
    p example_proxy.options
    super
  end

  def example_passed(example_proxy)
    puts "example_passed"
    p example_proxy.options
    super
  end

  def example_failed(example_proxy, counter, failure)
    puts "example_failed"
    p example_proxy.options
    super
  end

end

and spec:
require 'spec'

describe "optionsformatter" do

  before :all do
    options[:all] = "all"
  end

  before :each do
    options[:each] = "each"
  end

  it "one" do
    options[:it] = "passing"
  end

  it "two" do
    options[:it] = "failing"
    raise
  end

end

When running the spec, then output will be something like this:
example_group_started
{}
example_started
{}
example_passed
{:it=>"passing", :each=>"each"}
example_started
{}
example_failed
{:it=>"failing", :each=>"each"}

In short - it seems that when example_group_started is invoked, then
options set in before :all doesn't propagate into formatter (at least
I thought that this would be logical thing to happen). Secondly, there
isn't also anything in options when example_started is invoked and
only real place to get anything useful from options is from
example_passed or example_failed. Is this expected?

Happily it also shows options from before :each, which enabled me to
use "configure" from my environment file something similar to:

Spec::Runner.configure do |config|
  config.before(:each) {options[:browser] = BrowserClass.instance}
end

And in Formatter under example_failed to get the browser object. It
makes sense to get this browser object only for failing examples
anyway, since no screenshots are made for passing examples.

So now I don't have to explicitly set options from every example or
example group and it is done automatically :-)

Jarmo


On Oct 19, 1:18 am, David Chelimsky <dchelim... at gmail.com> wrote:
> # in the example
> it "does something" do
>   options[:browser] = Selenium.new(...)
>   ...
> end
>
> # in the formatter
> def example_started(example)
>   example.options[:browser] # => same browser created in the example
> end
>
> HTH,
> David


More information about the rspec-users mailing list