【问题标题】:Have logger's error message when not expecting any in rspec不期望 rspec 中有任何记录器的错误消息
【发布时间】:2020-08-11 15:10:56
【问题描述】:

在我的一个规范中,我有以下期望:

expect(Rails.logger).not_to receive(:error)

问题是当它失败时,我没有关于错误本身的有用信息:

     Failure/Error: expect(Rails.logger).not_to receive(:error)
     
       (#<ActiveSupport::Logger:0x000000000b85dfa8 @level=1, @progname=nil, @default_formatter=#<Logger::Formatter:0x000000000b85df08 @datetime_format=nil>, @formatter=#<ActiveSupport::Logger::SimpleFormatter:0x000000000b17f510 @datetime_format=nil, @thread_key="activesupport_tagged_logging_tags:93059720">, @logdev=#<Logger::LogDevice:0x000000000b85deb8 @shift_period_suffix=nil, @shift_size=nil, @shift_age=nil, @filename=nil, @dev=#<File:/home/circleci/myproject/log/test.log>, @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x000000000b85de40>>, @local_levels=#<Concurrent::Map:0x000000000b85dda0 entries=0 default_proc=nil>, @thread_hash_level_key=:"ThreadSafeLogger#96661460@level">).error(*(any args))
           expected: 0 times with any arguments
           received: 1 time with any arguments

有没有办法以某种方式获取错误的内容? 如果失败,我应该改变编写规范的方式吗?

在我的情况下,奇怪的部分似乎是 received: 1 time with any arguments,我期待像 received: 1 time with arguments: ("foo") 这样的东西。

【问题讨论】:

  • 我认为您应该更改另一种断言错误的方式。例如:expect { raise "oops" }.to raise_error(RuntimeError, "oops")
  • 这里我不是要断言错误,而是要断言没有错误。

标签: ruby-on-rails ruby rspec


【解决方案1】:

我在 rspec 文档中没有找到如何做到这一点,但这里有一个关于如何访问错误信息的想法:

allow(Rails.logger).to receive(:error) { |params| raise params.to_s }

这不是惯用的,但是当在记录器上调用 error 时,您的测试会中断

【讨论】:

    【解决方案2】:

    这有点 hacky,但您可以进行故意失败的测试以查看有关错误本身的信息

    expect(Rails.logger).to receive(:error).with('foo')
    

    【讨论】:

      猜你喜欢
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 2014-02-10
      相关资源
      最近更新 更多