2014-09-23 31 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 

这将传递一个实际的异常对象插入方法