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
我該如何簡單地測試一個方法在對象上被調用?我在這裏錯過了一個更大的圖片嗎?
是的,做到了,謝謝! – steel