RSpec: how to test Rails logger message expectations?

后端 未结 6 1043
囚心锁ツ
囚心锁ツ 2020-12-24 00:17

I am trying to test that the Rails logger receives messages in some of my specs. I am using the Logging gem.

Let\'s say that I have a class like this:



        
6条回答
  •  清酒与你
    2020-12-24 00:48

    While I agree you generally don't want to test loggers, there are times it may be useful.

    I have had success with expectations on Rails.logger.

    Using RSpec's deprecated should syntax:

    Rails.logger.should_receive(:info).with("some message")
    

    Using RSpec's newer expect syntax:

    expect(Rails.logger).to receive(:info).with("some message")
    

    Note: In controller and model specs, you have to put this line before the message is logged. If you put it after, you'll get an error message like this:

    Failure/Error: expect(Rails.logger).to receive(:info).with("some message")
           (#).info("some message")
               expected: 1 time with arguments: ("some message")
               received: 0 times
    

提交回复
热议问题