Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Forked from ryanb/quiz.rb
Created May 15, 2009 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save practicingruby/112309 to your computer and use it in GitHub Desktop.
Save practicingruby/112309 to your computer and use it in GitHub Desktop.
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment