ruby – 如何检查对rspec中构造函数调用的方法的调用?

如果我有一个构造函数调用一个函数的类,我如何检查它被调用和正确的次数

class MyClass
  def initialize(count)
    count.times{self.do_something}
  end

  def do_something
    # whatever
  end

end

我想说点什么

n = 4
MyClass.new(n).should_receive(:do_something).exactly(n).times
n = 2
MyClass.new(n).should_receive(:do_something).exactly(n).times

但是失败是因为在do_receive被附加到它之前调用了do_something(至少我认为这就是原因).

expected: 4 times with any arguments
received: 0 times with any arguments

或者从构造函数调用这样的东西是错误的,我应该重构?

此外,这个问题与此非常相似:

rspec: How to stub an instance method called by constructor?

但是我希望在过去的5年里,答案比设置短线新呼叫的手动实现更好.

解决方法

执行此操作的新语法如下:

allow_any_instance_of(ExampleClass).to receive(:example_method).and_return("Example")
expect_any_instance_of(ExampleClass).to receive(:example_method).and_return("Example")

See the docs

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...