Rnk Jangir
Rnk Jangir

Reputation: 741

Rspec Mocks on any_instance with exactly(n) times

I want to use Mocks in rspec tests like.

klass.any_instance.should_receive(:save).exactly(2).times.and_return(true)

but I get an error message like:

'The message "save" was received by <#Object> but has already been received by <#Object>'

Temporary I use stub but for accuracy want to use mocks

Upvotes: 14

Views: 6069

Answers (1)

SztupY
SztupY

Reputation: 10546

The documentation of any_instance.should_receive is:

Use any_instance.should_receive to set an expectation that one (and only one)
instance of a class receives a message before the example is completed.

So you have specified that exactly one object should receive the save call two times, and not that 2 objects should receive the save call one time.

If you want to count the calls done by different instances you'll have to be creative like:

save_count = 0
klass.any_instance.stub(:save) { save_count+=1 }
# run test
save_count.should == 2

Upvotes: 23

Related Questions