Rspec期望子方法调用而不会导致父方法失败

时间:2015-05-11 22:05:17

标签: ruby unit-testing 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语法显式返回结果,则expect子句会失败,因为RSpec已覆盖该方法。

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

如何简单地测试在对象上调用方法?我在这里错过了更大的图片吗?

1 个答案:

答案 0 :(得分:2)

试试这个:

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

这是class方法,对吧?如果没有,请将expect替换为expect_any_instance_of

有关and_call_original的更多信息,请here