我试图在我的一些测试中测试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会使其通过。)
有没有测试日志记录的好方法?