最佳答案
我正在尝试测试 Rails 日志记录器是否在我的一些规范中接收消息。我正在使用 伐木宝石。
假设我有一门这样的课:
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 会让它通过。)
测试日志记录的好方法是什么?