-
-
Save matflores/112547 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 "rubygems" | |
require "test/unit" | |
require "shoulda" | |
class QuizIO | |
attr_accessor :response, :should_calculate | |
def gets | |
if @should_calculate && @response =~ /What is (\d+) \+ (\d+)\?/ | |
return $1.to_i + $2.to_i | |
else | |
return -1 | |
end | |
end | |
def puts(s) | |
@response = s | |
end | |
end | |
class QuizTest < Test::Unit::TestCase | |
context "A Quiz" do | |
setup do | |
@io = QuizIO.new | |
@quiz = Quiz.new(@io, @io) | |
end | |
context "given a correct answer" do | |
setup { @io.should_calculate = true ; @quiz.problem } | |
should "get a 'Correct!' response" do | |
assert_equal 'Correct!', @io.response | |
end | |
end | |
context "given an incorrect answer" do | |
setup { @io.should_calculate = false ; @quiz.problem } | |
should "get an '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