ryanb (owner)

Revisions

gist: 112476 Download_button fork
public
Public Clone URL: git://gist.github.com/112476.git
Embed All Files: show embed
mockio.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class MockIO
  def initialize(receiver = nil)
    @buffer = ""
    @receiver = receiver || MockIO.new(self)
  end
  
  def gets
    1000.times do |n|
      sleep 0.01 if n > 800 # throttle if it seems to be taking a while
      unless @buffer.empty?
        content = @buffer
        @buffer = ""
        return content
      end
    end
    raise "MockIO Timeout: No content was received for gets."
  end
  
  # TODO make this thread safe
  def puts(str)
    @receiver << "#{str}\n"
  end
  
  def <<(str)
    @buffer << str
  end
  
  def start
    @thread = Thread.new do
      yield(@receiver)
    end
  end
end
quiz.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# COMMUNITY CHALLENGE
#
# This solution uses MockIO which is a generic class for mocking gets/puts.
# It executes the "start" block in a separate thread which allows calls to "gets"
# to wait for input.
#
class Quiz
  def initialize(input = STDIN, output = STDOUT)
    @input = input
    @output = output
  end
  
  def problem
    first = rand(10)
    second = rand(10)
    @output.puts "What is #{first} + #{second}?"
    answer = @input.gets
    if answer.to_i == first + second
      @output.puts "Correct!"
    else
      @output.puts "Incorrect!"
    end
  end
end
 
require "test/unit"
require "mockio"
 
class QuizTest < Test::Unit::TestCase
  def setup
    @io = MockIO.new
    @io.start { |io| Quiz.new(io, io).problem }
    first, second = @io.gets.scan(/\d+/)
    @total = first.to_i + second.to_i
  end
  
  def test_correct
    @io.puts @total
    assert_equal "Correct!", @io.gets.chomp
  end
  
  def test_incorrect
    @io.puts @total+1
    assert_equal "Incorrect!", @io.gets.chomp
  end
end