我正在使用一些spec_helper.rb方法来生成RSpec示例,其中一个示例依赖于来自另一个的数据。
示例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
示例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
我知道代码没有多大意义,但它遵循重要的实际代码(@tested_objects
变量)。
当我运行规范时,它找不到@tested_objects变量(我猜它在示例块内使用了另一个变量空间)。 有没有办法将变量传递到最终帮助方法的示例块内?
RSpec 2.5,Rails 3.0.4,Ruby 1.8.7
答案 0 :(得分:1)
根据具体情况,您可能需要before
或share_examples_for
。
解决方法:似乎it
只能看到局部变量。然后你可以试试这个:
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