RSpec:如何测试 Rails 记录器消息预期? [英] RSpec: how to test Rails logger message expectations?

查看:30
本文介绍了RSpec:如何测试 Rails 记录器消息预期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试 Rails 记录器是否在我的某些规范中接收消息.我正在使用 Logging gem.

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:

class BaseWorker

  def execute
    logger.info 'Starting the worker...'
  end

end

还有一个规范:

describe BaseWorker do

  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('Logging::Rails').as_null_object
    Logging::Rails.stub_chain(:logger, :info).and_return(logger_mock)

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
    Logging::Rails.unstub(:logger)
  end

end

我收到以下失败消息:

 Failure/Error: logger_mock.should_receive(:info).with('Starting worker...')
   (Double "Logging::Rails").info("Starting worker...")
       expected: 1 time
       received: 0 times

我尝试了几种不同的方法来使规范通过.这适用于例如:

I've tried out several different approaches to get the spec to pass. This works for example:

class BaseWorker

  attr_accessor :log

  def initialize
    @log = logger
  end

  def execute
    @log.info 'Starting the worker...'
  end

end

describe BaseWorker do
  it 'should log an info message' do
    base_worker = BaseWorker.new
    logger_mock = double('logger')
    base_worker.log = logger_mock

    logger_mock.should_receive(:info).with('Starting the worker...')
    base_worker.execute
  end
end

但是必须像这样设置一个可访问的实例变量似乎尾巴在这里摇摆不定.(实际上,我什至不确定为什么将记录器复制到 @log 会使其通过.)

But having to setup an accessible instance variable like that seems like the tail is wagging the dog here. (Actually, I'm not even sure why copying logger to @log would make it pass.)

测试日志记录的好方法是什么?

What's a good solution for testing the logging?

推荐答案

虽然我同意您通常不想测试记录器,但有时它可能很有用.

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

我在 Rails.logger 上取得了成功.

I have had success with expectations on Rails.logger.

使用 RSpec 不推荐使用的 should 语法:

Using RSpec's deprecated should syntax:

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

使用 RSpec 较新的 expect 语法:

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")
       (#<ActiveSupport::Logger:0x007f27f72136c8>).info("some message")
           expected: 1 time with arguments: ("some message")
           received: 0 times

这篇关于RSpec:如何测试 Rails 记录器消息预期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆