2014-09-23 48 views
0

我想模擬一個錯誤消息,以一個錯誤作爲參數並調用.backtrace。我的方法是這樣的:Rspec嘲笑一個錯誤,即.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 
+1

你從rspec那個斷言中得到了什麼輸出? – Discorick 2014-09-24 02:03:58

+0

@Discorick我更新了當前的錯誤信息。 – 2014-09-24 15:02:53

回答

1

基於該Rspec的錯誤消息,您的源失敗很簡單。在你的規範中,你傳遞一個字符串作爲錯誤。

error_message = "I'm sorry, Dave. I'm afraid I can't do that." 

的的log_error方法試圖稱之爲「回溯」的字符串,而不是一個實際的異常 試試這個:。

begin 
    raise "I'm sorry, Dave. I'm afraid I can't do that." 
rescue => error_message 
    tax_reconciler.log_error(error_message) 
end 

這將傳遞一個實際的異常對象插入方法