Can I use RSpec to mock stdin/stdout to test console reads & writes?

Viewed 9022

My Ruby program reads lines from stdin and uses puts to print to stdout (the terminal). Can I use RSpec to test the reads and writes? Can I inject a string to my program like it was written in stdin and at the same time check the output?

line = STDIN.read.chomp.split

Also, I have the reads and writes in a loop, until line[0] is "quit". Can I test while the loop is running or should I call subject.read_in and subject.write_out?

2 Answers

RSpec 3.0+

With RSpec 3.0, there is output matcher for this purpose:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr
Related