If I have a class where the constructor calls another function, how do I check that it was called and the right number of times?
class MyClass
def initialize(count)
count.times{self.do_something}
end
def do_something
# whatever
end
end
I want to say something like
n = 4
MyClass.new(n).should_receive(:do_something).exactly(n).times
n = 2
MyClass.new(n).should_receive(:do_something).exactly(n).times
but that fails because the call to do_something happens before should_receive gets attached to it (at least I think that's why).
expected: 4 times with any arguments
received: 0 times with any arguments
Or is it just wrong to call stuff like this from the constructor and I should refactor?
Also, this question is very similar to this one:
rspec: How to stub an instance method called by constructor?
but I'm hoping in the last 5 years the answer has gotten better than setting up manual implementations of a stubbed new
call.
The new syntax for doing this is as follows:
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
Expectations are meant to be placed before the code that will be expected to meet them.
MyClass.any_instance.should_receive(:do_something).exactly(1).time
MyClass.new
That should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With