I'm trying to test an elevator simulator program that runs in the console and requires user interaction. At the moment, my tests look like this:
gem 'minitest', '>= 5.0.0'
require 'minitest/spec'
require 'minitest/autorun'
require_relative 'elevator'
class SingleFloorElevator < Elevator
@@moves = ["2", "N"].each
def get_input; @@moves.next end
end
class MultiFloorElevator < Elevator
@@moves = ["2", "Y", "7", "Y", "4", "N"].each
def get_input; @@moves.next end
end
class InvalidElevetorOne < Elevator
@@moves = ["-2", "2"].each
def get_input; @@moves.next end
end
class InvalidElevatorTwo < Elevator
@@moves = ["2000", "5"].each
def get_input; @@moves.next end
end
class ElevatorTest < MiniTest::Test
def test_can_accept_and_move_to_floor
e = SingleFloorElevator.new
e.run
assert_equal(e.current_floor, 2)
end
def test_can_change_direction
e = MultiFloorElevator.new
e.run
assert_equal(e.going_down, true)
assert_equal(e.going_up, false)
end
describe "it can maintain a list of floor numbers" do
it "cannot travel below the ground floor" do
e = InvalidElevetorOne.new
e.enter_floor
assert_equal(e.floors.size, 1)
assert_equal(e.floors, [2])
end
it "cannot travel higher than the top floor" do
e = InvalidElevatorTwo.new
e.enter_floor
assert_equal(e.floors.size, 1)
assert_equal(e.floors, [5])
end
end
end
As you can see, I'm overriding the Elevator class (more important the get_input
method which grabs user input from the console) multiple times according to what I need to test. It all works perfectly fine but I was wondering if there was a tidier way of doing things?