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”))
#!/usr/bin/env rubyputs “look at me run”
expect { system %(./runner)) }
.to output(a_string_including(“look at me run”))

Matching Strings

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

Where does it go?

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”
RSpec.describe CLI do
specify do
expect { CLI.call }.to output(
a_string_including(“Thanks for stopping by”)

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”))


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