如果我有一个构造函数调用另一个函数的类,我如何检查它被调用和正确的次数?
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")