【问题标题】:mocking an error message in Rspec when method calls .backtrace当方法调用 .backtrace 时在 Rspec 中模拟错误消息
【发布时间】:2014-09-23 21:22:18
【问题描述】:

我有一个记录错误的方法。它以错误消息作为参数,但现在它需要一个完整的错误并在其上调用 .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

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing rspec


    【解决方案1】:

    我会这样做:

    describe '#log_error' do
      let(:time)    { 'Tue, 16 Sep 2014 20:18:19 UTC +00:00' }
      let(:message) { 'The message' }
      let(:error)   { double(:message => message, :backtrace => []) }
      let(:line)    { 'RECONCILE_TAX_RATES [2014-09-16 20:18:19 UTC] ERROR [The message]' }
    
      subject(:tax_reconciler) { TaxReconciler.new }
    
      before { allow(STDOUT).to receive(:puts) }
    
      it 'logs errors' do
        Timecop.freeze(time) do
          tax_reconciler.log_error(error)
          expect(STDOUT).to have_receive(:puts).with(line)
        end
      end
    end
    

    【讨论】:

    • 当我尝试这种方式时,我得到:#<:core::examplegroup::nested_1::nested_4:0x007fa0048ad238> 的未定义方法“允许”
    • allow 方法与 rspec-mocks gem 一起提供。见:github.com/rspec/rspec-mocks
    • 我在应用程序中有 rspec-mocks,但版本较旧(2.12.2.)。这个旧版本是否支持语法?该应用程序非常大,所以如果 3.1.1 不向后兼容,我不想更新和破坏所有其他测试。
    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多