Skip to content

Instantly share code, notes, and snippets.

@ljsc
Forked from ryanb/quiz.rb
Created May 15, 2009 18:57
Show Gist options
  • Save ljsc/112378 to your computer and use it in GitHub Desktop.
Save ljsc/112378 to your computer and use it in GitHub Desktop.
# COMMUNITY CHALLENGE
#
# Here's my (@ljsc) solution. I guess this would qualifiy as a mock.
#
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 QuizTest < Test::Unit::TestCase
class Responder
def initialize; @queue = [] end
def to_a; [self, self] end
attr_reader :gets
def expect(pattern, &blk)
@queue << [pattern, blk]
end
def puts(str)
pattern, handler = @queue.shift
if match = str.match(pattern)
@gets = handler[*match] if handler
else
raise Test::Unit::AssertionFailedError, %Q[#{str.inspect} did not match #{pattern.inspect}]
end
end
end
def setup
@responder = Responder.new
@quiz = Quiz.new(*@responder)
end
def test_correct
@responder.expect %r[What is (\d+) \+ (\d+)?] do |_, a, b|
a.to_i + b.to_i
end
@responder.expect 'Correct!'
@quiz.problem
end
def test_incorrect
@responder.expect %r[What is (\d+) \+ (\d+)?] do |_, a, b|
a.to_i + b.to_i + 1
end
@responder.expect 'Incorrect!'
@quiz.problem
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment