2015-05-11 16 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