【发布时间】:2014-09-23 21:22:18
【问题描述】:
我有一个记录错误的方法。它以错误消息作为参数,但现在它需要一个完整的错误并在其上调用 .backtrace。方法如下:
def log_error(error)
puts error.backtrace
puts "RECONCILE_TAX_RATES [#{Time.now}] ERROR [#{error.message}]"
end
我正在尝试对其进行测试,但我无法弄清楚测试的语法。我之前有的是:
it 'logs errors' do
time = "Tue, 16 Sep 2014 20:18:19 UTC +00:00"
Timecop.freeze(time) do
tax_reconciler = TaxReconciler.new
error_message = "I'm sorry, Dave. I'm afraid I can't do that."
expected = "RECONCILE_TAX_RATES [2014-09-16 20:18:19 UTC] ERROR [I'm sorry, Dave. I'm afraid I can't do that.]"
STDOUT.should_receive(:puts).with(expected)
tax_reconciler.log_error(error_message)
end
end
我尝试了 rSpec 文档中的各种组合,但我一直被 .backtrace 方法绊倒。如何模拟此错误消息以使 .backtrace 不会爆炸?提前感谢您的帮助,如果我需要提供更多信息,请告诉我。
编辑:对于任何有类似问题的人,我使用的解决方案是:
it 'logs errors' do
time = "Tue, 16 Sep 2014 20:18:19 UTC +00:00"
Timecop.freeze(time) do
expected = "RECONCILE_TAX_RATES [2014-09-16 20:18:19 UTC] ERROR [I'm sorry, Dave. I'm afraid I can't do that.]"
tax_reconciler = TaxReconciler.new
begin
raise "I'm sorry, Dave. I'm afraid I can't do that."
rescue => error_message
STDOUT.should_receive(:puts).with(expected)
STDOUT.should_receive(:puts).with(error_message.backtrace)
tax_reconciler.log_error(error_message)
end
end
end
【问题讨论】:
标签: ruby-on-rails ruby unit-testing rspec