Skip to content

Instantly share code, notes, and snippets.

@josevalim josevalim/quiz.rb forked from ryanb/quiz.rb
Created May 15, 2009

Embed
What would you like to do?
# COMMUNITY CHALLENGE
#
# How would you test this Quiz#problem method? Only two rules:
#
# 1. You must test the order the gets/puts happen. The tests should not
# still pass if "gets" happens before "puts", etc.
#
# 2. No changing the Quiz class implementation/structure. But you can
# use whatever framework you want for the tests.
#
# Note: The first rule used to be "no mocking" but I changed it. If you
# can accomplish the first rule with mocks then go ahead. I'm looking
# for the simplest/cleanest solution whatever that may be.
#
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"
class Responder
attr_accessor :response, :result
def puts(message)
if message.match(/What is (\d+) \+ (\d+)\?/)
self.result = caculate($1.to_i, $2.to_i).to_s
else
self.response = message
end
end
alias :gets :result
end
class GoodResponder < Responder
def caculate(a, b)
a + b
end
end
class BadResponder < Responder
def caculate(a, b)
(a + b).next
end
end
class QuizTest < Test::Unit::TestCase
def test_correct
io = GoodResponder.new
quiz = Quiz.new(io, io)
quiz.problem
assert_equal 'Correct!', io.response
end
def test_incorrect
io = BadResponder.new
quiz = Quiz.new(io, io)
quiz.problem
assert_equal 'Incorrect!', io.response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.