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
How to Compare Strings Ignoring the Case
Installing Ruby on MAC Os X 10.8.2
Ruby on Rails - "Add 'Gem SQLite3'' to Your Gemfile"
Rails - Whenever Gem - Dynamic Values
Base64 Photo and Paperclip -Rails
How to Test a File Upload in Rails
How to Get the Name of the Command Called for Usage Prompts in Ruby
How to Access the Rack Environment from Within Rails
Gem Install Error (Sass Compass)
How to Print Out the Contents of an Object in Rails for Easy Debugging
How to Reference a Function in Ruby
What Does the * (Star) Mean in Ruby
Project Euler 1:Find the Sum of All the Multiples of 3 or 5 Below 1000
Rails Gem Rails3-Jquery-Autocomplete How to Scope by User