在rspec中不希望出现记录器时出现记录器错误消息

问题描述

在我的一种规格中,我有以下期望:

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")这样的东西。

解决方法

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

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

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

,

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...