How to ignore extra messages with RSpec should_receive?

Spec:

before do Logger.should_receive( :write ).with 'Log message 1' end it 'works' do get '/' end 

Sinatra app:

 get '/' Logger.write( 'Log message 1' ) Logger.write( 'Log message 2' ) end 

This specification fails due to "Log message 2". How to tell RSpec to ignore any other messages and only check the expected message?

+6
source share
2 answers

You need to drown out the method that will receive the message before the expected message.

 # RSpec < 3 Logger.stub(write: nil) 

The stub method is deprecated in RSpec 3 , use one of the following instead

 # RSpec >= 3 allow(Logger).to receive(:write).and_return(nil) # Most appropriate in this case allow(Logger).to receive(:write) { nil } # Prefer block when returning something of a dynamic nature, eg a calculation allow(Logger).to receive_messages(write: nil) # Prefer hash when stubbing multiple methods at once, eg receive_messages(info: nil, debug: nil) 

The stub method is an instruction for an object (real or double test) to return a known value in response to a message.

In this case, tell the Logger object to return nil when it receives a write message (first time).

So your before block should look like this:

 before do Logger.stub(write: nil) Logger.should_receive(:write).with('Log message 1') end 
+5
source

This question is a bit old, but, finding my way here, I thought I would answer it, assuming rspec-mocks v3.

Preliminarily completing the object, then the have_received works well when you make sure that the object receives a specific message, and not just that .

Subtle difference between receive(:...) and have_received(:...)

To get to the original question and assuming that it was rewritten in rspec-mocks v3, my solution would be the following:

 allow(Logger).to receive(:write) get '/' expect(Logger).to have_received(:write).with('Log message 1') 

Note that it is important to put the statement at the end when it checks the state of the stub when called, and not on completion, as is customary.

+1
source

All Articles