Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to say "should_receive" more times in RSpec

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)
like image 286
Jakub Arnold Avatar asked Aug 25 '09 13:08

Jakub Arnold


People also ask

What is RSpec double?

RSpec features doubles that can be used as 'stand-ins' to mock an object that's being used by another object. Doubles are useful when testing the behaviour and interaction between objects when we don't want to call the real objects - something that can take time and often has dependencies we're not concerned with.

What is allow in RSpec?

Use the allow method with the receive matcher on a test double or a real. object to tell the object to return a value (or values) in response to a given. message. Nothing happens if the message is never received.

How do I set up RSpec?

Installing RSpec Boot up your terminal and punch in gem install rspec to install RSpec. Once that's done, you can verify your version of RSpec with rspec --version , which will output the current version of each of the packaged gems. Take a minute also to hit rspec --help and look through the various options available.


2 Answers

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

Hope it helps =)

like image 93
Staelen Avatar answered Oct 12 '22 23:10

Staelen


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)
like image 43
Uri Agassi Avatar answered Oct 12 '22 23:10

Uri Agassi