How to say "should_receive" more times in RSpec How to say "should_receive" more times in RSpec ruby-on-rails ruby-on-rails

How to say "should_receive" more times in RSpec


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 =)


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)


@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.