Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created July 11, 2019 15:02
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save myronmarston/d9a699c1c0c74b992ceb1bbe6b4b2c6c to your computer and use it in GitHub Desktop.
Save myronmarston/d9a699c1c0c74b992ceb1bbe6b4b2c6c to your computer and use it in GitHub Desktop.
class Example
def initialize(input: $stdin, output: $stdout)
@input = input
@output = output
end
def ask_for_number
@output.puts "Input an integer 5 or above"
loop do
input = @input.gets.to_i
return true if input >= 5
@output.puts "Invalid. Try again:"
end
end
end
require 'stringio'
RSpec.describe Example do
context 'with input greater than 5' do
it 'asks for input only once' do
output = ask_for_number_with_input(6)
expect(output).to eq "Input an integer 5 or above\n"
end
end
context 'with input equal to 5' do
it 'asks for input only once' do
output = ask_for_number_with_input(5)
expect(output).to eq "Input an integer 5 or above\n"
end
end
context 'with input less than 5' do
it 'asks repeatedly, until a number 5 or greater is provided' do
output = ask_for_number_with_input(2, 3, 6)
expect(output).to eq <<~OUTPUT
Input an integer 5 or above
Invalid. Try again:
Invalid. Try again:
OUTPUT
end
end
def ask_for_number_with_input(*input_numbers)
input = StringIO.new(input_numbers.join("\n") + "\n")
output = StringIO.new
example = Example.new(input: input, output: output)
expect(example.ask_for_number).to be true
output.string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment