Rspec嘲笑调用.backtrace的错误?

时间:2014-09-23 19:36:32

标签: ruby-on-rails unit-testing 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 个答案:

答案 0 :(得分:1)

根据Rspec错误消息,您的失败来源很简单。在您的规范上,您将传递一个字符串作为错误。

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

log_error方法正在尝试调用' backtrace"在字符串上,而不是实际的异常。 试试这个:

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

这会将实际的异常对象传递给您的方法。