我正在尝试测试 Rails 记录器是否接收到我的某些规范中的消息。我正在使用Logging gem。
假设我有这样的课程:
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
我尝试了几种不同的方法来让规范通过。这适用于例如:
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
但是必须设置一个这样的可访问实例变量似乎在这里摇尾巴。(实际上,我什至不确定为什么将 logger 复制到 @log 会使其通过。)
什么是测试日志记录的好解决方案?