Skip to content

Instantly share code, notes, and snippets.

@alexvollmer
Forked from ryanb/quiz.rb
Created May 15, 2009 17:55
Show Gist options
  • Save alexvollmer/112341 to your computer and use it in GitHub Desktop.
Save alexvollmer/112341 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment