How to Validate Exits and Aborts in Rspec

How can I validate exits and aborts in RSpec?

try this:

module MyGem
describe "CLI" do
context "execute" do

it "should exit cleanly when -h is used" do
argv=["-h"]
out = StringIO.new
lambda { ::MyGem::CLI.execute( out, argv) }.should raise_error SystemExit
end

end
end
end

How to spec methods that exit or abort

Simply put your assertions outside of the lambda, for example:

class Foo
attr_accessor :result

def logic_and_exit
@result = :bad_logic
exit
end
end

describe 'Foo#logic_and_exit' do
before(:each) do
@foo = Foo.new
end

it "should set @foo" do
lambda { @foo.logic_and_exit; exit }.should raise_error SystemExit
@foo.result.should == :logics
end
end

When I run rspec, it correctly tells me:

expected: :logics
got: :bad_logic (using ==)

Is there any case where this wouldn't work for you?

EDIT: I added an 'exit' call inside the lambda to hande the case where logic_and_exit doesn't exit.

EDIT2: Even better, just do this in your test:

begin
@foo.logic_and_exit
rescue SystemExit
end
@foo.result.should == :logics

Test exit! with RSpec

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

How do I write a bash script to abort a rspec test if it fails

You can just use normal exit codes, since bundle exec rspec will preserve the exit code from rspec. E.g.

#!/bin/bash
if ! bundle exec rspec spec/ --format documentation --fail-fast; then
echo "failed rspec test"
else
echo "rspec test passed; Warbalize Now!!!!!"
fi

How do I abort RSpec if setup fails?

You don't need any special RSpec magic for this - just test that your service is running in your spec_helper.rb, and raise an exception if it's not running.

if service_not_running
raise "Service is not running. Please start it with {whatever}."
end

This will cause your rspec suite to immediately fail when it starts, with a helpful error that helps the programmer get the service started.



Related Topics



Leave a reply



Submit