Skip to content

Instantly share code, notes, and snippets.

@nakajima
Forked from ryanb/quiz.rb
Created May 15, 2009 20:23
Show Gist options
  • Select an option

  • Save nakajima/112418 to your computer and use it in GitHub Desktop.

Select an option

Save nakajima/112418 to your computer and use it in GitHub Desktop.
could be better, could be worser
# COMMUNITY CHALLENGE
#
# How would you test this Quiz#problem method? Only two rules:
#
# 1. The tests should fail if any part of the application breaks.
# For example: If "gets" is moved before "puts" then the tests should
# fail since that breaks the application.
#
# 2. You cannot change the Quiz class. But you can use whatever framework
# and tools you want for the tests. (RSpec, Cucumber, etc.)
#
# 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 QuizTest < Test::Unit::TestCase
def new_quiz(*args)
Quiz.new(*args)
end
class EagerQuizIO < StringIO
def initialize(buffer, &block)
@algorithm = block
super
end
def puts(*args)
super
first, second = args.first.scan(/\d+/).flatten
first and second ?
@answer = @algorithm.call(first.to_i, second.to_i) : nil
end
def gets
@answer || super
end
end
def test_correct
io = EagerQuizIO.new(result='') { |x, y| x + y }
quiz = new_quiz(io, io)
quiz.problem
assert result.include?('Correct!')
end
def test_incorrect
io = EagerQuizIO.new(result='') { |x, y| x + y + 1 }
quiz = new_quiz(io, io)
quiz.problem
assert result.include?('Incorrect!')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment