【发布时间】:2020-03-19 09:41:39
【问题描述】:
我想测试我在代码中生成的特定日志。虽然测试Rails.logger 似乎相当简单,但我将它包装在ActiveSupport::TaggedLogging 中,我无法使用它进行测试......
我有两种方法:
def logger
@logger = ActiveSupport::TaggedLogging.new(Rails.logger)
end
def log(message)
logger.tagged('MangaDex::Importer', "User ##{@current_user_id}") do
logger.info message
end
end
然后我在我的代码中这样调用它:
if md_parsed_list.blank?
log 'List is inaccessible'
return
end
现在,在我的 Rspec 测试中,我一直在尝试做这样的事情:
it 'logs and stops execution if there is nothing to import' do
expect(Spiders::Mangadex).to receive(:parse!)
.with(:parse, url: import_url)
.and_return({})
expect(ActiveSupport::TaggedLogging).to receive(Rails.logger)
expect(Rails.logger).to receive(:info).with('List is inaccessible')
expect(CreateMangaEntries).not_to receive(:call)
described_class.perform_async(import_url, user.id)
described_class.drain
end
我知道我在连接 TaggedLogging 和 Rails.logger 时缺少一些步骤,因为调用上面的测试只会引发错误 undefined method 'to_sym' for #<ActiveSupport::Logger:0x00007f8fc545db50>。
希望得到一些帮助,在此先感谢!
编辑:
在基于@Grzegorz 改进了所涉及的模拟之后,测试最终看起来像这样:
let(:tagged_logger_double) { instance_double(ActiveSupport::Logger) }
it 'logs and stops execution if MDList is inaccessible' do
expect(Spiders::Mangadex).to receive(:parse!)
.with(:parse, url: import_url)
.and_return(nil)
expect(ActiveSupport::TaggedLogging)
.to receive(:new)
.with(Rails.logger)
.and_return(tagged_logger_double)
expect(CreateMangaEntries).not_to receive(:call)
expect(tagged_logger_double).to receive(:info).with('List is inaccessible')
described_class.perform_async(import_url, user.id)
described_class.drain
end
由于ActiveSupport::TaggedLogging 的实例为ActiveSupport::Logger,我不得不稍微更改双精度。
我能够解决原始异常,但仍然无法测试 receive(:info),因为 tagged 似乎丢失了:
#<InstanceDouble(ActiveSupport::Logger) (anonymous)> received unexpected message :tagged with ("MangaDex::Importer", "User #2626")
但是当我尝试存根该方法时:allow(tagged_logger_double).to receive(:tagged),我得到这样的方法不存在的错误:the ActiveSupport::Logger class does not implement the instance method: tagged,我仍然坚持测试失败。
【问题讨论】:
标签: ruby-on-rails logging rspec ruby-on-rails-6