sandal (owner)

Fork Of

Revisions

gist: 112309 Download_button fork
public
Public Clone URL: git://gist.github.com/112309.git
Embed All Files: show embed
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# COMMUNITY CHALLENGE
#
# How would you test this Quiz#problem method? No mocks/stubs allowed.
#
# (Here's @seacreature's take)
 
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 "stringio"
require "test/unit"
 
class Input
  def initialize(output)
    @output = output
    @handler = nil
  end
 
  def handle_output(pattern, &block)
    @handler = [pattern, block]
  end
 
  def gets
     pattern, block = @handler
     block[@output.string.match(pattern)]
  end
end
 
class QuizTest < Test::Unit::TestCase
 
  def setup
     @output = StringIO.new
     @input = Input.new(@output)
     @quiz = Quiz.new(@input, @output)
  end
 
  def test_correct
    @input.handle_output /What is (\d) \+ (\d)/ do |m|
      m[1].to_i + m[2].to_i
    end
    
    @quiz.problem
 
    assert_equal "Correct!\n", @output.string.to_a.last
  end
  
  def test_incorrect
    @input.handle_output /What is (\d) \+ (\d)/ do |m|
      m[1].to_i + m[2].to_i - 1
    end
 
    @quiz.problem
    assert_equal "Incorrect!\n", @output.string.to_a.last
  end
 
end