Testing command line tool output with RSpec

Joe James
Joe James
Sep 3, 2018 · 3 min read
expect { system %(echo “gotta love rspec”) }
.to output(a_string_including(“gotta love rspec”))
.to_stdout_from_any_process
#!/usr/bin/env rubyputs “look at me run”
expect { system %(./runner)) }
.to output(a_string_including(“look at me run”))
.to_stdout_from_any_process

Matching Strings

expect { system %(echo “hello command line world”) }
.to output(“hello command line world”)
.to_stdout_from_any_process
# => expected block to output “hello command line world” to stdout, but output “hello command line world\n”

Where does it go?

RuntimeError:
You must chain `to_stdout` or `to_stderr` off of the `output(…)` matcher.
expect { puts “from the same process” }.to output(“from the same process”).to_stdout
module CLI
def self.call
puts “Thanks for stopping by”
end
end
RSpec.describe CLI do
specify do
expect { CLI.call }.to output(
a_string_including(“Thanks for stopping by”)
).to_stdout
end
end

Testing Errors

#!/usr/bin/env rubyNoConfig = Class.new(StandardError)
raise NoConfig, “no configuration”
RSpec.describe “crash” do
subject { system “./crash” }
it { expect { subject }.to output.to_stderr_from_any_process } specify “must be configured” do
expect { system “./crash” }
.to output(a_string_including(“no configuration”))
.to_stderr_from_any_process
end
end

Conclusion

Joe James

Written by

Joe James

Remote programmer, finds himself asking questions at 5am and writing down the thought process.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade