【问题标题】:Object.any_instance should_receive vs expect() to receiveObject.any_instance should_receive vs expect() 接收
【发布时间】:2013-07-08 03:35:27
【问题描述】:

以下代码按预期工作:

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

【问题讨论】:

    标签: rspec rspec2 rspec-rails


    【解决方案1】:

    现在有一个没有很好记录的方法expect_any_instance_of 可以处理any_instance 的特殊情况。你应该使用:

    expect_any_instance_of(Object).to receive(:subscribe)
    

    谷歌expect_any_instance_of了解更多信息。

    【讨论】:

    • +1 表示“没有很好的记录”。还是这样。 rubydoc.info/gems/rspec-mocks/RSpec/Mocks/…
    • 我一直在使用allow_any_instance_of。是不是这个方法的别名?
    • @rubyprince 它们是不同的,允许方法存根行为和期望方法测试行为。例如,allow(my_obj).to receive(:method_name).and_return(true) stubs my_obj.method_name() 因此,如果在测试中调用它,它只会返回 trueexpect(my_obj).to receive(:method_name).and_return(true) 不会改变任何行为,但如果 my_obj.method_name() 在稍后的测试中没有被调用或不返回 true,则会设置一个测试预期失败。
    • 谢谢@Saigo。现在说得通了。
    • 不推荐使用此语法。在今天的语法中是否有关于如何做到这一点的任何提示?
    【解决方案2】:

    请注意,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)
    

    祝你好运! ??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多