Tests – your safety net
Ruby checks types only at runtime – a typo won't surface until the code actually runs. That's why tests are a fixture of Ruby projects. The tool is already on board: Minitest ships with Ruby.
A test is a class inheriting from Minitest::Test; every method starting with test_ is a test case. assert_equal expected, actual checks equality. Here in the notebook, run_tests starts the test run:
class Duration
attr_reader :minutes
def initialize(minutes)
@minutes = minutes
end
def in_hours
minutes / 60.0
end
end
class TestDuration < Minitest::Test
def test_in_hours
assert_equal 1.5, Duration.new(90).in_hours
end
def test_zero_minutes
assert_equal 0.0, Duration.new(0).in_hours
end
end
run_testsReading the report: 2 runs (two test methods), 2 assertions (two checks), 0 failures, 0 errors – all green. And when something breaks? Minitest shows you exactly what was expected and what arrived:
class TestBroken < Minitest::Test
def test_deliberately_wrong
assert_equal 100, Duration.new(90).minutes
end
end
run_testsThere you put tests into their own files and run them directly – minitest/autorun makes them run automatically when the program ends:
# test/test_duration.rb
require "minitest/autorun"
require_relative "../lib/duration"
class TestDuration < Minitest::Test
def test_in_hours
assert_equal 1.5, Duration.new(90).in_hours
end
end$ ruby test/test_duration.rb
2 runs, 2 assertions, 0 failures, 0 errors, 0 skipsMore helpers: assert, refute, assert_nil, assert_raises, and setup for shared preparation. RSpec is the best-known alternative with its own language (expect(x).to eq(y)).
Entry. Write TestEntry with at least two tests: one for a valid entry, one for invalid cases (negative hours or empty project). Finish with run_tests – everything must be green. From now on: no exercise without tests!class Entry
attr_reader :project, :hours
def initialize(project, hours)
@project = project
@hours = hours
end
def valid?
hours > 0 && !project.to_s.empty?
end
end
# class TestEntry < Minitest::Test
# def test_...
# end
# end
# run_tests