如何在rspec中测试rescue子句中的代码
我的代码中有以下模式: 关键是我们需要以静默方式记录错误,但是如果代码中有错误,测试就需要失败如何在rspec中测试rescue子句中的代码,rspec,Rspec,我的代码中有以下模式: 关键是我们需要以静默方式记录错误,但是如果代码中有错误,测试就需要失败 begin self.a_method_call some_other_object.a_method_that_has_been_refactored rescue StandardError => e Rails.logger.error e.backtrace end 如果由于self.a\u method\u call和some\u other\u object.a\u m
begin
self.a_method_call
some_other_object.a_method_that_has_been_refactored
rescue StandardError => e
Rails.logger.error e.backtrace
end
如果由于
self.a\u method\u call
和some\u other\u object.a\u method\u已重构
之间的交互而引发错误,则rescue标准错误将消除任何错误,并通过测试代码块的任何测试。如果begin子句中的代码有错误,如何使救援静音,以便测试失败?错误日志记录是其功能的一部分。捕获错误日志,而不是使救援静音
如书面所述,您可以通过。用于配置希望接收的参数Rails.logger.error
。由于您不知道将接收到什么,您可以使用各种匹配器来检查您得到的backtrace
返回的数组
it 'logs the backtrace as an error' do
# This comes before you call the method to set up the mock which expects
# to be called.
expect(Rails.logger).to receive(:error)
.with(instance_of(Array))
thing.some_method
end
因为这将替换Rails.logger
,如果在过程中有任何其他内容,则某些方法调用Rails.logger
测试将失败
我们可以通过一个小的重构来简化这个过程。不要直接使用Rails.logger
,而是将其作为一个属性
class SomeClass
attr_accessor :logger
def initialize
@logger = Rails.logger
end
def some_method
a_method_call
some_other_object.a_method_that_has_been_refactored
rescue StandardError => e
logger.error e.backtrace
end
end
现在我们可以专门模拟thing.logger
返回的内容
it 'logs the backtrace as an error' do
# This comes before you call the method to set up the mock which expects
# to be called.
expect(thing.logger).to receive(:error)
.with(instance_of(Array))
thing.some_method
end
回答得很好。谢谢我可以通过不调用rails.logger来解决这个问题。