以下代码按预期工作:
Object.any_instance.should_receive(:subscribe)
但是当使用新的 rspec 期望时它不起作用:
expect(Object.any_instance).to receive(:subscribe)
错误是:
expected: 1 time with any arguments
received: 0 times with any arguments
我怎样才能使这个工作与 expect() 接收?
以下代码按预期工作:
Object.any_instance.should_receive(:subscribe)
但是当使用新的 rspec 期望时它不起作用:
expect(Object.any_instance).to receive(:subscribe)
错误是:
expected: 1 time with any arguments
received: 0 times with any arguments
我怎样才能使这个工作与 expect() 接收?
现在有一个没有很好记录的方法被称为expect_any_instance_of处理any_instance特殊情况。你应该使用:
expect_any_instance_of(Object).to receive(:subscribe)
谷歌expect_any_instance_of了解更多信息。
expect_any_instance_of根据Jon Rowe(关键 rspec 贡献者)的说法,只是提醒一下,现在被认为是不推荐使用的行为。建议的替代方法是使用该instance_double方法创建类的模拟实例,并期望对该实例的调用是双精度的,如该链接中所述。
Jon 的方法是首选(因为它可以用作通用的测试辅助方法)。但是,如果您发现这令人困惑,希望您的示例案例的这个实现可以帮助理解预期的方法:
mock_object = instance_double(Object) # create mock instance
allow(MyModule::MyClass).to receive(:new).and_return(mock_object) # always return this mock instance when constructor is invoked
expect(mock_object).to receive(:subscribe)
祝你好运!