2015-05-11 20 views
0

我希望能夠簡單地測試一個方法在另一個方法中被調用,而不需要測試任何其他方法。Rspec期望子方法調用而不會導致父方法失敗

讓我們假設我有一個方法可以進行內部服務調用。

class Foo 
    def self.perform 
    result = InternalService.call 
    ... 
    result.attribute_method # do stuff with result 
    end 
end 

InternalService擁有所有自己的單元測試,我不想在這裏重複這些測試。不過,我仍然需要測試InternalService正在被調用。

如果我使用Rspec的expect語法,它將剔除InternalService.call,並且該方法的其餘部分將失敗,因爲不會有結果。

allow_any_instance_of(InternalService).to receive(:call).and_return(result) 
Foo.perform 

=> NoMethodError: 
=> undefined method `attribute_method' 

如果我需要Rspec的allow語法明確地返回結果,因爲RSpec的已覆蓋的方法的expect條款失效。

allow_any_instance_of(InternalService).to receive(:call).and_return(result) 
expect_any_instance_of(InternalService).to receive(:call) 
Foo.perform 

=> Failure/Error: Unable to find matching line from backtrace 
=> Exactly one instance should have received the following message(s) but didn't: call 

我該如何簡單地測試一個方法在對象上被調用?我在這裏錯過了一個更大的圖片嗎?

回答

2

試試這個:

expect(InternalService).to receive(:call).and_call_original 
Foo.perform 

這是一個class方法,對嗎?如果不是,請將expect替換爲expect_any_instance_of

更多關於and_call_original可以找到here

+0

是的,做到了,謝謝! – steel