Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: Testing logger messages for block syntax

I currently use a logger in the following way:

def log_stuff
  logger.info { 'Info log message' }
  logger.debug { expesive_action }
end

But I would like to know if the logger receives the correct message with RSpec.

If I would just pass the logging line to the input this would have been easy:

# logger.info('Info log message')
expect(logger_mock).to receive(:info).with('Info log message')

But I couldn't figure out a way I could do something like this with the block syntax.

I specifically want to use this syntax, so that expensive_action only gets called when the log level is set to DEBUG.

like image 430
leifg Avatar asked Jan 21 '14 10:01

leifg


1 Answers

It's not that difficult, though a tad trickier than vanilla expectations:

  expect(logger_mock).to receive(:info) do |&block|
    expect(block.call).to eq('Info log message')
  end

in this case, &block in your spec is simply the block you have in logger.info call. So you must explicitly call it, and then set another expectation on the return value. That's how I do it, at least.

like image 99
EdvardM Avatar answered Oct 17 '22 07:10

EdvardM