2013-07-10 37 views
67

下面的代碼按預期工作:Object.any_instance should_receive VS預期()接收

Object.any_instance.should_receive(:subscribe) 

但使用新RSpec的期待時,它不工作:

expect(Object.any_instance).to receive(:subscribe) 

錯誤是:

expected: 1 time with any arguments 
received: 0 times with any arguments 

我該如何使expect()來接收這個工作?

回答

141

現在有一個記錄不太好的方法,稱爲expect_any_instance_of,它處理any_instance特例。您應該使用:

expect_any_instance_of(Object).to receive(:subscribe) 

Google expect_any_instance_of瞭解更多信息。

+0

+1對於「記錄不完善」。仍然如此。 http://www.rubydoc.info/gems/rspec-mocks/RSpec/Mocks/ExampleMethods:expect_any_instance_of – johngraham

+0

我一直在使用'allow_any_instance_of'。這是這種方法的別名嗎? – rubyprince

+0

@rubyprince它們不同,使用允許方法存根行爲並期望方法測試行爲。例如,'allow(my_obj).to接收(:method_name)。和_return(true)'存根'my_obj.method_name()',所以如果在測試中調用它,它只是返回'true'。 (my_obj).to receive(:method_name).and_return(true)'不會改變任何行爲,但是如果在後面沒有調用my_obj.method_name(),則設置測試期望失敗。測試或不返回true。 – Saigo

相關問題