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:

class InputFaker
  def feedStrings(strings)
    @strings = strings
  def gets
    next_string = @strings.shift
    next_string #TODO: I guess next_string is superflous
Second the output faker
class OutputFaker
  def initialize
  def write(str)
    @result << str.chomp
  def clear
  def result
Third, setup and teardown methods
  def setup
    $stdin = InputFaker.new
    $stdout = OutputFaker.new
    @robotUI=RobotUI.new unless @robotUI
  def teardown
    $stdin = STDIN
    $stdout = STDOUT
And fourth, the actual use (in this case a test)
  def actual_test(array_of_inputs,expected_output)

First published here