문제

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