How can I test with RSpec some code with #exit!?

def method
  ...
rescue MyError => e
  logger.error "FATAL ERROR"
  exit! 1
end

I can test this code with #exit method because raise the SystemExit exception.

it "logs a fatal error" do
  lambda do
    object.method
    expect(logger).to have_received(:error).with("FATAL ERROR")
  end
end

it "exits" do
  expect { object.method }.to raise_error(SystemExit)
end

I'm not sure if I can achieve something similar. I'm thinking to reimplement the exit! method in Kernel module, just only for the specs. Any ideas?

有帮助吗?

解决方案

You can stub the exit! method for the object:

it "logs a fatal error" do
  lambda do
    allow(object).to receive(:exit!)
    object.method
    expect(logger).to have_received(:error).with("FATAL ERROR")
  end
end

it "exits" do
  expect(object).to receive(:exit!)

  object.method
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top