-
-
Save jimweirich/112411 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 | |
###################################################################### | |
# SOLUTION 2 - Using mocks | |
###################################################################### | |
require 'rubygems' | |
require 'test/unit' | |
require 'shoulda' | |
require 'flexmock/test_unit' | |
class QuizTestWithMocks < Test::Unit::TestCase | |
context "A Quiz" do | |
setup do | |
@mock_io = flexmock("IO") | |
@mock_io.should_receive(:puts).with("What is 2 + 3?").once.ordered | |
@quiz = Quiz.new(@mock_io, @mock_io) | |
flexmock(@quiz).should_receive(:rand).and_return(2, 3) | |
end | |
context 'when given the correct answer' do | |
setup do | |
@mock_io.should_receive(:gets).and_return("5\n").once.ordered | |
end | |
should 'receive a Correct response' do | |
@mock_io.should_receive(:puts).with("Correct!").once.ordered | |
@quiz.problem | |
end | |
end | |
context 'when given an incorrect answer' do | |
setup do | |
@mock_io.should_receive(:gets).and_return("6\n").once.ordered | |
end | |
should 'receive an Incorrect response' do | |
@mock_io.should_receive(:puts).with("Incorrect!").once.ordered | |
@quiz.problem | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment