1

I am trying to write an Rspec test for my script that will pass if my script fails gracefully.

if options[:file] == false
  abort 'Missing an argument'
end

Rspec:

it 'if the file argument is not given, it provides a helpful message' do
  expect(`ruby example_file.rb`).to eq('Missing an argument')
end

My test continues to fail and says

expected: 'Missing an argument'
got: ''

I am not sure why it returns an empty string. I have looked at these posts with no luck:

If you need any more information about my script let me know. Thank you.

Community
  • 1
  • 1
  • 1
    You would not typically want to use RSpec to test a script by running it from the command line using backticks. When you do that you lose the context you need for testing things with your desired level of control. You hand off the execution to the shell (Bash, Cmd, etc.) and then wait for it to return a value or output some text to stdout or stderr – Midwire Dec 29 '15 at 20:30

1 Answers1

1

abort/exit will both print to stderr, whereas your rspec is listening on the stdout channel. Try the following:

expect(`ruby example_file.rb`).to output('Missing an argument').to_stderr
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
  • It appears that now RSpec [requires block syntax for the output matcher](https://relishapp.com/rspec/rspec-expectations/v/3-7/docs/built-in-matchers/output-matcher) (_e.g.,_ `expect { \`ruby example_file.rb\` }.to ...`) – Ryan Lue May 08 '18 at 02:59
  • This by itself doesn't stop an `abort` or `exit 1` that is encountered in your source from causing **rspec itself** to abort prematurely, which can happen if you're using ruby as a shell scripting language. In fact, rspec will still print its final summary messages, and might not even warn you that any specs "failed". (However, the `$?` value captured by your shell will still be non-zero.) We ran into this after we added a console script to our Rails app with corresponding rspec tests and didn't catch the exit case right away-- our suite would just exit after a random number of examples. – beporter Sep 27 '21 at 21:46
  • This [other StackOverflow answer](https://stackoverflow.com/a/28047771/70876) did the trick for me. – beporter Sep 27 '21 at 21:55