2

I want to test that echo 1 outputs 1, but

expect { `echo 1` }.to output("1").to_stdout

does not work. It says it outputs nothing to stdout, while

expect { print 1 }.to output("1").to_stdout

works just fine. Why doesn't the first one work?

1
  • 1
    expect { echo 1 }.to eq '1' ? Commented Feb 23, 2016 at 15:18

1 Answer 1

4
expect { `echo 1` }.to output("1").to_stdout

doesn't work for two reasons:

  1. echo runs in a subprocess. RSpec's output matcher doesn't handle output from subprocesses by default. But you can use to_stdout_from_any_process instead of to_stdout to handle subprocesses, although it's a bit slower.

  2. output only works for output sent to the same standard output stream as the Ruby process. Backticks open a new standard output stream, send the command's standard output to it and return the contents of the stream when the command completes. I don't think you care whether you run your subprocess with backticks or some other way, so just use system (which sends the command's standard output to the Ruby process's standard output stream) instead.

Addressing those two points gives us this expectation, which passes:

expect { system("echo 1") }.to output("1\n").to_stdout_from_any_process

(I had to change the expected value for it to pass, since echo adds a newline.)

As MilesStanfield pointed out, in the case you gave it's equivalent and easier to just test the output of backticks rather than use output:

expect { `echo 1` }.to eq "1\n"

That might or might not work in the more complicated case that you presumably have in mind.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.