2014-06-11 34 views
0

我在我的應用程序位於spec/support/utilities.rb 我想傳遞一個模型對象給它的一個實例,一個輔助方法,但我還沒有成功,因此測試失敗傳遞一個模型實例來一個輔助方法在RSpec的測試

這裏是輔助方法

def attribute_not_present(model_instance,model_attrib) 
    describe "when #{model_attrib} is not present" do 
    before { model_instance.send("#{model_attrib}=", " ") } 
     it { should_not be_valid } 
    end 
end 

spec/model/tool_spec.rb我有這個

​​

@tool小號EEMS不要在助手

樣本故障識別是這個

1) Tool when size is not present 
    Failure/Error: before { model_instance.send("#{model_attrib}=", " ") } 
    NoMethodError: 
    undefined method `size=' for nil:NilClass 
    # ./spec/support/utilities.rb:3:in `block (2 levels) in attribute_not_present' 

我軌新受

+0

這看起來有點像你正在重新創建共享示例 –

+0

沒有真正在使用Rpsec以編程方式在哪裏避免相同類型的代碼。我正在幹代碼 –

回答

1

在調用attribute_not_present時,@ tool仍不存在。此外,在一種情況下,self是示例組,其中規範實際運行時(以及在您之前的塊內)self是示例組的實例。

你並不需要通過在所有雖然通過model_instance - 你可以改爲只使用subject

before { subject.send("#{model_attrib}=", " ") } 

但是。

您可能還想看看共享示例。

0

好了 - 我想我明白你想在這裏做什麼。你正在嘗試進行單元測試,特別是你的Tool類的驗證,是嗎?

如果是這樣,我個人喜歡使用shoulda_matchers寶石,我發現這是非常地道的。

舉個例子,你可以這樣做:

describe Tool do 
    it { should validate_presence_of(:kind) } 
    it { should validate_presnece_of(:serial_number) } 
end 

你甚至可以與驗證做多,說你知道:serial_number只能是一個整數,你可以這樣做:

it { should validate_numericality_of(:serial_number).only_integer } 

這可能是一種比輔助方法更好的單元級驗證方法,因爲它更像Ruby。

+0

感謝您的洞察力,我會在另一個測試中使用它 –

相關問題