Object.any_instance should_receive vs expect()接收

时间:2013-07-10 09:11:46

标签: rspec rspec2 rspec-rails

以下代码按预期工作:

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()接收?

2 个答案:

答案 0 :(得分:147)

现在有一个名为expect_any_instance_of的文档没有很好的文档处理any_instance特例。你应该使用:

expect_any_instance_of(Object).to receive(:subscribe)

Google expect_any_instance_of了解更多信息。

答案 1 :(得分:1)

请注意,expect_any_instance_of现在根据Jon Rowe (key rspec contributor)被视为过时的行为。建议的替代方法是使用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)

祝你好运! ??