Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 spec fails because of 'Log message 2'. How to tell RSpec to ignore any other messages, and only test for the expected message?

like image 987
B Seven Avatar asked Dec 10 '13 18:12

B Seven


1 Answers

You need to stub the method that will be receiving the message before the message expectation.

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

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

# 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, e.g. a calculation
allow(Logger).to receive_messages(write: nil)  # Prefer hash when stubbing multiple methods at once, e.g. receive_messages(info: nil, debug: nil)

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

In this case, tell the Logger object to return the value nil when it receives the write message (the 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
like image 134
Ash Wilson Avatar answered Sep 25 '22 20:09

Ash Wilson