TDD Beyond Basics : How to Fake User Input

Discussion


I used highline gem to test drive my pair ranking gem, rasam. I knew that StringIO can be used in tests as VirtualFile to simulate File. But how do you simulate user input? Reading the source code of the highline library, I came across HighLine::Simulate class that simulates user input that can be used in tests. It uses meta-programming. It is based on the gist by Jason Morrison. I have simplified the original gist. Here is the source:

require 'test/unit'

class VirtualInput
  def initialize(strings)
    @strings = strings
  end

  def gets
    next_string = @strings.shift
    # Uncomment the following line if you'd like to see the faked $stdin#gets
    puts "(DEBUG) Faking #gets with: #{next_string}"
    next_string
  end

  def self.with_fake_input(strings)
    $stdin = VirtualInput.new(strings)
    yield
  ensure
    $stdin = STDIN
  end
end

class Waiter
  attr_accessor :orders

  def take_orders
    self.orders = {}

    puts "Hello, diner.  What is your name?"
    name = gets

    puts "Please to meet you. #{name}, what would you like for dinner?"
    order = gets

    orders[name] = order
  end
end

class WaiterTest < Test::Unit::TestCase
  def test_ordering
    VirtualInput.with_fake_input(["Harry", "The tarte tomate"]) do
      waiter = Waiter.new
      waiter.take_orders

      assert waiter.orders.has_key?("Harry")
      assert_equal "The tarte tomate", waiter.orders["Harry"]
    end
  end
end

You can see how the with_fake_input hijacks the $stdin value to the VirtualInput and reverts it back once it completes.

We can use Highline::Simulate class to automate the script that tests the rasam gem. This will be useful to write our acceptance test.

Summary


In this article, you learned how to simulate user input so that we can write tests without having to manually enter the data to the script.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.