2010-04-20 33 views
0

我試圖做類似如下:Shoulda:如何在設置之外使用實例變量或應該阻止?

@special_attributes = Model.new.methods.select # a special subset 
@special_attributes.each do |attribute| 
    context "A model with #{attribute}" do 
    setup do 
     @model = Model.new 
    end 
    should "respond to it by name" do 
     assert_respond_to @model, attribute 
    end 
    end 
end 

然而,@special_attributes超出範圍運行單元測試時,留下我與第2行nil對象我想不出在哪裏/如何定義它以將其納入範圍。有什麼想法嗎?

回答

0

明白了(我認爲)。 Shoulda正在Shoulda :: Context的上下文中執行該塊。在上面的例子中,@special_attributes是我的測試類的一個實例變量,而不是Shoulda :: Context。要解決這個問題,而不是使用實例變量,只需在上下文塊中使用局部變量即可。

因此,舉例來說:

context "Model's" do 
    model = Model.new 
    special_attributes = model.methods.select # a special subset 
    special_attributes.each do |attribute| 

    context "attribute #{attribute}" do 
     setup do 
     @model = model 
     end 
     should "should have a special characteristic" 
     assert_respond_to @model, attribute 
     ... 
     end 
    end 

    end 
end 
相關問題