Object.any_instance should_receive vs expect() to receive

Calin picture Calin · Jul 10, 2013 · Viewed 26.2k times · Source

The following piece of code works as expected:

Object.any_instance.should_receive(:subscribe)

But when using the new rspec expectation it does not work:

expect(Object.any_instance).to receive(:subscribe)

The error is:

expected: 1 time with any arguments
received: 0 times with any arguments

How can I make this work with expect() to receive?

Answer

Peter Alfvin picture Peter Alfvin · Jul 10, 2013

There's now a not very well documented method called expect_any_instance_of that handles the any_instance special case. You should use:

expect_any_instance_of(Object).to receive(:subscribe)

Google expect_any_instance_of for more info.