【发布时间】:2014-09-23 19:36:32
【问题描述】:
我正在尝试为将错误作为参数并在其上调用 .backtrace 的方法模拟错误消息。我的方法看起来像:
def log_error(error)
puts error.backtrace
puts "RECONCILE_TAX_RATES [#{Time.now}] ERROR [#{error.message}]"
end
我在放入 error.backtrace 行之前的测试如下:
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
现在该方法已更改为接收错误而不仅仅是一条消息,我对如何编写测试感到困惑。任何帮助表示赞赏,如果我需要包含更多信息,请告诉我。
the error I am getting is:
Failure/Error: tax_reconciler.log_error(error_message)
NoMethodError:
undefined method `backtrace' for "I'm sorry, Dave. I'm afraid I can't do that.":String
所以按照下面的建议我试过了
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.]"
STDOUT.should_receive(:puts).with(expected)
tax_reconciler = TaxReconciler.new
begin
raise "I'm sorry, Dave. I'm afraid I can't do that."
rescue => error_message
tax_reconciler.log_error(error_message)
end
end
end
好的,下面建议的解决方案如下:
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
【问题讨论】:
-
你从 rspec 收到了关于该断言的什么输出?
-
@Discorick 我更新了我当前的错误消息。感谢收看。
标签: ruby-on-rails unit-testing rspec