In Ruby, I need to print a feedback message and then exit with a status code of 1.
class Foo
def bar
puts "error"
exit 1
end
end
In RSpec, how can I ignore exit 1 when expecting the feedback message to be printed?
it "returns a feedback message" do
expect { Foo.new.bar }.to output(/no error/i).to_stdout
end
If I run the spec above, no failure is raised.
Finished in 0.02402 seconds (files took 0.17814 seconds to load)
1 example, 0 failures
asked Jun 3, 2025 at 10:30
Sig
6,15012 gold badges64 silver badges104 bronze badges
2 Answers 2
exit raises a SystemExit error. You can rescue it like any other error or expect to raise_error:
RSpec.describe Foo do
it "returns a feedback message" do
expect { Foo.new.bar }
.to output(/no error/i).to_stdout
.and raise_error(SystemExit)
end
end
answered Jun 3, 2025 at 23:36
Alex
31.3k10 gold badges69 silver badges86 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Stefan
Nice one, I always forget, that Ruby's
exit doesn't exit right away. (which is what exit! does)You could use allow to capture the exit message inside your Foo instance:
describe '#bar' do
let(:foo) { Foo.new }
it "returns a feedback message" do
allow(foo).to receive(:exit)
expect { foo.bar }.to output(/no error/i).to_stdout
end
end
This will effectively install a new method Foo#exit that does nothing by default, see the RSpec docs on
Allowing messages.
answered Jun 3, 2025 at 18:36
Stefan
115k14 gold badges157 silver badges234 bronze badges
Comments
lang-rb