Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Created April 10, 2012 22:39
Show Gist options
  • Save stevenharman/2355172 to your computer and use it in GitHub Desktop.
Save stevenharman/2355172 to your computer and use it in GitHub Desktop.
Rspec matchers for testing exit codes.
require 'rspec/expectations'
module ExitCodeMatchers
extend RSpec::Matchers::DSL
matcher :terminate do
actual = nil
match do |block|
begin
block.call
rescue SystemExit => e
actual = e.status
end
actual and actual == status_code
end
chain :with_code do |status_code|
@status_code = status_code
end
failure_message_for_should do |block|
"expected block to call exit(#{status_code}) but exit" +
(actual.nil? ? " not called" : "(#{actual}) was called")
end
failure_message_for_should_not do |block|
"expected block not to call exit(#{status_code})"
end
description do
"expect block to call exit(#{status_code})"
end
def status_code
@status_code ||= 0
end
end
end
describe HerpDerps do
# Fails with
# NameError:
# undefined local variable or method `terminate' for
# #<RSpec::Core::ExampleGroup::Nested_1::Nested_3::Nested_1:0x007ff96bac96f0>
it 'exits cleanly' do
# expecting call to `exit`
-> { described_class.run }.should terminate
end
it 'exits with non-zero status code' do
#expecting call to `abort` or `exit(false)`
-> { described_class.run }.should terminate.with_code(1)
end
end
@marhan
Copy link

marhan commented Jul 12, 2012

Thanks, very useful.

@mmasashi
Copy link

Thanks for the convenient matcher. I've modified it for rspec 3.
https://gist.github.com/mmasashi/58bd7e2668836a387856

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment