alexvollmer (owner)

Fork Of

Revisions

gist: 112341 Download_button fork
public
Public Clone URL: git://gist.github.com/112341.git
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
# SOLUTION: just use the StringIO class and replace Kernel#rand with a fixture method. We're
# not interested in testing how rand works so explicitly setting the value is fine.
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 "stringio"
 
class QuizTest < Test::Unit::TestCase
  def setup
    @in = StringIO.new
    @out = StringIO.new
    @quiz = Quiz.new(@in, @out)
    class << @quiz
      def rand(ignore)
        1
      end
    end
  end
  
  def test_correct
    @in << "2"
    @in.rewind
    @quiz.problem
    @out.rewind
    assert_equal ["What is 1 + 1?\n", "Correct!\n"], @out.readlines
  end
  
  def test_incorrect
    @in << "1"
    @in.rewind
    @quiz.problem
    @out.rewind
    assert_equal ["What is 1 + 1?\n", "Incorrect!\n"], @out.readlines
  end
end