在方法调用.backtrace时在Rspec中模拟错误消息

时间:2014-09-23 21:22:18

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

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

1 个答案:

答案 0 :(得分: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