Skip to content

Instantly share code, notes, and snippets.

@protocarl
Forked from joshknowles/quiz.rb
Created May 15, 2009 19:32
Show Gist options
  • Save protocarl/112394 to your computer and use it in GitHub Desktop.
Save protocarl/112394 to your computer and use it in GitHub Desktop.
# COMMUNITY CHALLENGE
#
# How would you test this Quiz#problem method? Only two rules:
#
# 1. No mocks or stubs allowed. I'm looking for a other alternatives.
# Mocks can get messy in complex scenarios, and this is intended to
# be a high level test which executes all code. I don't think mocking
# would be a very clean solution anyway, but if you want to try it
# and prove me wrong feel free.
#
# 2. No changing the Quiz class implementation/structure. But you can
# use whatever framework you want for the tests.
#
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
Kernel.module_eval do
def rand(n)
@rand ||= [1,2]
@rand.shift or raise
end
end
def test_correct
@input = StringIO.new('3', 'r')
@output = StringIO.new('', 'w')
Quiz.new(@input, @output).problem
assert_equal "What is 1 + 2?\nCorrect!\n", @output.string
end
def test_incorrect
@input = StringIO.new('jello', 'r')
@output = StringIO.new('', 'w')
Quiz.new(@input, @output).problem
assert_equal "What is 1 + 2?\nIncorrect!\n", @output.string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment