【问题标题】:Rspec mocking an error that .backtrace is called on?Rspec嘲笑.backtrace被调用的错误?
【发布时间】: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


【解决方案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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多