问题 指定对象在RSpec中不接收任何消息


我知道如何指定对象不应该收到特定的消息:

expect(File).to_not receive(:delete)

我如何指定它根本不应该收到任何消息?就像是

expect(File).to_not receive_any_message

6479
2018-04-09 05:01


起源

这里的背景是什么?为什么你需要这样做? - meagar♦
我想这样做来测试一个无操作,即没有创建,更新,删除等。 - Kris


答案:


听起来你只想用一个没有预期的双重替换有问题的对象(所以任何方法调用都会导致错误)。在你的确切情况下,你可以做到

stub_const("File", double())

13
2018-04-11 15:00





我不确定用例是什么。但以下是我能想出的唯一直接答案:

methods_list = File.public_methods # using 'public_methods' for clarity
methods_list.each do |method_name|
  expect(File).to_not receive(method_name)
end

如果你想要涵盖所有方法(即不仅仅是 public 那些):

# readers, let me know if there is a single method to
# fetch all public, protected, and private methods
methods_list = File.public_methods +
               File.protected_methods +
               File.private_methods

1
2018-04-09 06:08



我希望,我有一个值得分享的用例。我在模块级别的模块中公开服务,并且想要确保在输入数据上检测到错误的情况下不会请求服务。通过禁止发送到该服务的任何消息,我按名称摆脱了connascence(正如已故Jim Weirich所解释的那样)并且我的测试相对于服务中的API更改并不脆弱。 - lab419