Created
April 10, 2012 22:39
-
-
Save stevenharman/2355172 to your computer and use it in GitHub Desktop.
Rspec matchers for testing exit codes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Thanks, very useful.