127

I have this in my test

Project.should_receive(:find).with(@project).and_return(@project)

but when object receive that method call two times, I have to do

Project.should_receive(:find).with(@project).and_return(@project)
Project.should_receive(:find).with(@project).and_return(@project)

Is there any way how to say something like

Project.should_receive(:find).with(@project).and_return(@project).times(2)
Jakub Arnold
  • 85,596
  • 89
  • 230
  • 327

4 Answers4

226

This is outdated. Please check Uri's answer below

for 2 times:

Project.should_receive(:find).twice.with(@project).and_return(@project)

for exactly n times:

Project.should_receive(:find).exactly(n).times.with(@project).and_return(@project)

for at least n times:

Project.should_receive(:msg).at_least(n).times.with(@project).and_return(@project)

more details at https://www.relishapp.com/rspec/rspec-mocks/v/2-13/docs/message-expectations/receive-counts under Receive Counts

starball
  • 20,030
  • 7
  • 43
  • 238
Staelen
  • 7,691
  • 5
  • 34
  • 30
85

The new expect syntax of rspec will look like this:

for 2 times:

expect(Project).to receive(:find).twice.with(@project).and_return(@project)

for exactly n times:

expect(Project).to receive(:find).exactly(n).times.with(@project).and_return(@project)

for at least n times:

expect(Project).to receive(:msg).at_least(n).times.with(@project).and_return(@project)
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93
0

should_receive, as opposed to any_instance, expects that the class receives message the specified number of times.

any_instance on the other hand is generally used for stubbing a method.

So the first case is an expectation that we would like to test, while the second one is getting past a method to the next line so we can move on.

Drenmi
  • 8,492
  • 4
  • 42
  • 51
amnsan
  • 41
  • 6
  • 1
    Drenmi I appreciate the time you have taken to add a few comma's to a post I had added almost a year ago... It did not look like there was any change to the technical aspect of the answer... Why would you down vote me for this...? – amnsan Dec 29 '15 at 05:40
0

@JaredBeck pointed out. The solution didn't work for me on any_instance call.

For any instance i ended up using stub instead of should_receive.

Project.any_instance.stub(:some_method).and_return("value")

This will work for any no. of times though.

Prasanna
  • 10,956
  • 2
  • 28
  • 40