14

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

SztupY
  • 10,291
  • 8
  • 64
  • 87
Rnk Jangir
  • 711
  • 6
  • 23
  • possible duplicate of [How to say "any\_instance" "should\_receive" any number of times in RSpec](http://stackoverflow.com/questions/9800992/how-to-say-any-instance-should-receive-any-number-of-times-in-rspec) – SztupY Jul 10 '13 at 10:33

1 Answers1

23

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
Community
  • 1
  • 1
SztupY
  • 10,291
  • 8
  • 64
  • 87
  • 1
    i want two different object to should_receive(:save) in one example. Actually i am creating 'n' new object through looping and want to test it hit the save method. Sorry for my bad English. – Rnk Jangir Jan 17 '13 at 11:06
  • You have to use my second example then – SztupY Jan 17 '13 at 11:08