Kostas
Kostas

Reputation: 8585

In RSpec, how can one pass an instance variable to an example block?

I am using some spec_helper.rb methods to generate RSpec examples and one of them is dependent on data from another one.

Example spec_helper.rb:

def it_should_be_big(objects)
  @tested_objects ||= []

  objects.each do |obj|
    it "should be big (#{obj.name})" do
      obj.should be_big
    end
  end

  @tested_objects += objects
end

def it_should_be_small(objects)
  @tested_objects ||= []

  objects.each do |obj|
    it "should be small (#{obj.name})" do
      obj.should be_small
    end
  end

  @tested_objects += objects
end

def it_should_have_tested_for_all_objects
  it "should test for all objects" do
    @tested_objects ||= []

    (all_objects - @tested_objects).should == []

    @tested_objects = []
  end
end

Example something_spec.rb:

describe "something" do
  it_should_be_big(some_objects)
  it_should_be_small(some_other_objects)

  it_should_have_tested_for_all_objects
end

I know the code does not make much sense but it follows the actual code where it matters (the @tested_objects variable).

When I run the specs, it can't find the @tested_objects variable (I guess it uses another variable space for inside the example blocks). Is there a way to pass the variable to inside the example block of the final helper method?

RSpec 2.5, Rails 3.0.4, Ruby 1.8.7

Upvotes: 1

Views: 2068

Answers (1)

Emiliano Poggi
Emiliano Poggi

Reputation: 24816

Depending on the situation you may want before or share_examples_for.


workaround: it seems that only local variables are seen by the it. Then you can try this:

def it_should_have_tested_for_all_objects
  @tested_objects ||= []

  tested_objects = @tested_objects
  it "should test for all objects" do
    (all_objects - tested_objects).should == []
  end

  @tested_objects = []
end

Upvotes: 1

Related Questions