Reputation: 3285
i have a method that logs errors. It was taking an error message as a parameter but now it takes an entire error and calls .backtrace on it. The method is below:
def log_error(error)
puts error.backtrace
puts "RECONCILE_TAX_RATES [#{Time.now}] ERROR [#{error.message}]"
end
I am trying to test it and I cant figure out the syntax for the test. WHat I had before is:
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
I have tried various combinations from the rSpec docs but I keep getting tripped up on the .backtrace method. How can I mock this error message so that .backtrace doesn't blow up? Thanks in advance for your help and let me know if I need to give anymore information.
Edit: For anyone with a similar problem the solution I used was:
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
Upvotes: 1
Views: 491
Reputation: 106882
I would do it like this:
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
Upvotes: 1