Faking the console in Ruby
A few days ago, I was preparing an assignment for a job process both in Java and in Ruby. While doing in Java, I decided to test the engine. But in Ruby I wanted to test the whole application, including the communication via standard input/output on the console.
And how do you mock standard input/output in Ruby?. Well. It turns out it is quite easy to do it with Rspec. But I wanted to do it without any additional requirement. How do you mock STDIN and STDOUT in plain Ruby.
It turns out it isn’t difficult. Based on this gist, I prepared my own solution. First the input faker:
Second the output fakerclass InputFakerdef feedStrings(strings)@strings = stringsenddef getsnext_string = @strings.shiftnext_string #TODO: I guess next_string is superflousendend
Third, setup and teardown methodsclass OutputFakerdef initialize@result=[]enddef write(str)@result << str.chompenddef clear@result=[]enddef result@result.joinendend
And fourth, the actual use (in this case a test)def setup$stdin = InputFaker.new$stdout = OutputFaker.new@robotUI=RobotUI.new unless @robotUIenddef teardown$stdin = STDIN$stdout = STDOUTend
def actual_test(array_of_inputs,expected_output)$stdin.feedStrings(array_of_inputs)array_of_inputs.size.times{@robotUI.parse()}assert_equal(expected_output,$stdout.result)end
First published here