Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec expect something before expect raise_error

Imagine there's a method that rescues and does some logging.

def do_something
  # do stuff
  some_client.call(var1)
rescue StandardError => e
  # log some stuff.
  Rails.logger.error("#{self.class} - Var 1 is #{var1}.") if e.is_a?(MyError)

  raise
end

Then in the RSpec, I'd like to

  • assert the error is raised.
  • it logs the error
before do
  allow(Rails.logger).to receive(:error)
  allow(some_client).to receive(:call).and_raise(MyError)
end

it "logs the error" do
  subject

  expect(Rails.logger).to have_received(:error).with(/some message with var1/)
end

it "raises MyError" do
  expect { subject }.to raise_error(MyError)
end

expect { subject }.to raise_error(MyError) part is working as expected, but how should I assert the logging? With the example code above, RSpec will report the error on the raised error without asserting the logging.

like image 694
Yi Zeng Avatar asked Apr 06 '26 00:04

Yi Zeng


1 Answers

Just put them both in the same it. Expect that it raises an error and logs it.

it "raises MyError and logs it" do
  expect { subject }.to raise_error(MyError)
  expect(Rails.logger).to have_received(:error).with(/some message with var1/)
end

Alternatively if you really want to check that it logs the error in a separate it you'll have to rescue the error. Otherwise your spec will fail (unhandled error)

it "logs the error" do
  subject
rescue
ensure
  expect(Rails.logger).to have_received(:error).with(/some message with var1/)
end
like image 66
Siim Liiser Avatar answered Apr 08 '26 14:04

Siim Liiser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!