Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Forked from ryanb/quiz.rb
Created May 15, 2009 20:04
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 jimweirich/112410 to your computer and use it in GitHub Desktop.
Save jimweirich/112410 to your computer and use it in GitHub Desktop.
# 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
######################################################################
# SOLUTION 1 - Using no mocks
######################################################################
require 'rubygems'
require 'test/unit'
require 'shoulda'
class QuizTestWithoutMocks < Test::Unit::TestCase
class PassingIO
attr_reader :response
attr_writer :correct_answer
def initialize
@correct_answer = true
end
def puts(str)
if str =~ /What is (\d+) \+ (\d+)\?/
@answer = calculate_answer($1.to_i, $2.to_i)
else
@response = str
end
end
def gets
"#{@answer}\n"
end
private
def calculate_answer(first, second)
if @correct_answer
first + second
else
first + second + 1
end
end
end
context 'A Quiz' do
setup do
@io = PassingIO.new
@quiz = Quiz.new(@io, @io)
end
context 'when given the correct answer' do
setup do
@io.correct_answer = true
@quiz.problem
end
should 'get a Correct response' do
assert_equal "Correct!", @io.response
end
end
context 'when given an incorrect answer' do
setup do
@io.correct_answer = false
@quiz.problem
end
should 'get a Incorrect response' do
assert_equal "Incorrect!", @io.response
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment