2

I have a method that will sometimes call exit(numeric_value).

Is it possible for rspec to validate that when the method is invoked, the process is exiting with the correct value?

I have seen these other posts, but they do not answer this specific question.

Community
  • 1
  • 1
Travis Bear
  • 13,039
  • 7
  • 42
  • 51
  • You would need to stub out `exit`, or your program will actually *exit* when that line is encountered. You really shouldn't just be bailing out that way though. Raise an exception instead. – user229044 Dec 06 '13 at 19:50
  • @meagar The ruby script I want to test with rspec is used in the context of an external framework (Sensu) that examines the exit value and acts accordingly. So calling `exit` seems to be required in this case. – Travis Bear Dec 06 '13 at 19:52
  • 2
    Ah, I didn't realize `exit` in Ruby actually *does* raise an Exception. Your question is a duplicate of the first link you posted, and the answer will work fine for you. Just catch the `SystemExit` exception. `lambda { whatever }.should raise_error SystemExit`, or just catch the `SystemExit` exception your self an inspect `.status` of the caught exception. ` – user229044 Dec 06 '13 at 19:57
  • @meagar I know I can just catch the SystemExit exception. The problem I don't know how to solve is: how to verify that we exited with status code 1, for example, or 2. – Travis Bear Dec 06 '13 at 20:01
  • As I said: Test `.status` of the exception you catch. – user229044 Dec 06 '13 at 20:24
  • @meagar Now I see what you were getting at, thanks for the info. If you submit this as an answer, I will accept it. – Travis Bear Dec 06 '13 at 23:23

1 Answers1

8

Given sample ruby code:

def it_will_exit
  puts "before exit"
  exit(false)
  puts "never get here"
end

rspec test case can be:

it "it must exit" do
  expect { it_will_exit }.raise_exception(SystemExit)
end

it "the exit value should be false" do
  begin
    it_will_exit
  rescue SystemExit=>e
    expect(e.status).to eq(1)
  end
end
shawnzhu
  • 7,233
  • 4
  • 35
  • 51