0
我有一個記錄錯誤的方法。它將一個錯誤消息作爲一個參數,但現在它需要一個完整的錯誤並在其上調用.backtrace。方法如下:在方法調用時模仿Rspec中的錯誤消息.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
當我嘗試這樣我得到:未定義的方法'允許'for# –
2014-09-23 22:25:26
'allow'方法附帶'rspec-mocks' gem。請參閱:https://github.com/rspec/rspec-mocks – spickermann 2014-09-24 00:52:34
我有rspec-mocks在應用程序,但舊版本(2.12.2。)。這個舊版本是否支持語法?該應用程序非常大,所以如果3.1.1不向後兼容,我不想更新和打破所有其他測試。 – 2014-09-24 16:31:05