Have logger's error message when not expecting any in rspec

Viewed 145

In one of my spec, I have the following expectation:

expect(Rails.logger).not_to receive(:error)

The problem is when it fails, I have no useful information about the error itself:

     Failure/Error: expect(Rails.logger).not_to receive(:error)
     
       (#<ActiveSupport::Logger:0x000000000b85dfa8 @level=1, @progname=nil, @default_formatter=#<Logger::Formatter:0x000000000b85df08 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x000000000b17f510 @datetime_format=nil, @thread_key="activesupport_tagged_logging_tags:93059720">, @logdev=#<Logger::LogDevice:0x000000000b85deb8 @shift_period_suffix=nil, @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/home/circleci/myproject/log/test.log>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x000000000b85de40>>, @local_levels=#<Concurrent::Map:0x000000000b85dda0 entries=0 default_proc=nil>, @thread_hash_level_key=:"ThreadSafeLogger#96661460@level">).error(*(any args))
           expected: 0 times with any arguments
           received: 1 time with any arguments

Is there a way to get the content of the error somehow? Should I change the way I write the spec to get it in case of failure?

It seems in my case the odd part is received: 1 time with any arguments, where I was expecting something like received: 1 time with arguments: ("foo").

2 Answers

I did not find how to do that in the rspec documentation, but here's an idea of how you could access the error information:

allow(Rails.logger).to receive(:error) { |params| raise params.to_s }

It is not as idiomatic but your test breaks when error is called on the logger

It's a bit hacky, but you can make a deliberately failing test in order to see information about the error itself

expect(Rails.logger).to receive(:error).with('foo')
Related