Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 372
Rnk Jangir Avatar asked Jan 17 '13 06:01

Rnk Jangir


Video Answer


1 Answers

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
like image 126
SztupY Avatar answered Oct 05 '22 19:10

SztupY