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

Rspec Expect Child Method Invocation Without Causing Parent Method To Fail

我希望能够简单地测试一个方法是否在另一个方法中被调用,而无需测试任何其他内容。

假设我有一个进行内部服务调用的方法。

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 语法显式 return 结果,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

我怎样才能简单地测试一个方法是否正在对象上调用?我在这里错过了更大的画面吗?

试试这个:

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

这是一个class方法,对吧?如果不是,请将 expect 替换为 expect_any_instance_of

有关 and_call_original 的更多信息,请参见 here