Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check calls to a method called from constructor in rspec?

Tags:

ruby

rspec

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.

like image 868
xaxxon Avatar asked Dec 21 '22 02:12

xaxxon


2 Answers

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

like image 121
Automatico Avatar answered Dec 30 '22 08:12

Automatico


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.

like image 29
Leo Correa Avatar answered Dec 30 '22 08:12

Leo Correa