2011-05-09 64 views
1

我正在使用一些spec_helper.rb方法來生成RSpec示例,其中一個依賴於另一個數據。在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,紅寶石1.8.7

回答

1

根據不同的情況下,你可能希望beforeshare_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 

+0

這在我的情況下並不合理。我需要在多個示例之間共享一個變量(不好),或者在示例之外設置它,但是可以從示例中訪問它。 – Kostas 2011-05-09 21:03:10

+0

@vrinek:看看我的編輯可能的解決方案。然而,在我的愚見,你不應該使用這樣的助手:) – 2011-05-10 07:38:07

相關問題