Testing with Minitest
| Your first assertion | |
| ruby -Itest | |
| Describe blocks | |
| Red green refactor |
Your first assertion
Minitest ships with Ruby tooling as the default small test framework. A test class inherits from Minitest::Test and every method starting with test_ runs as one test.
Install it first with the steps in
Gems and Bundler.
require "minitest/autorun"
class TestMath < Minitest::Test
def test_addition
assert_equal 4, 2 + 2
end
end
ruby -Itest
Test files usually live in a test folder with project code loaded beside them. The minus capital I flag adds that folder to the load path, so require finds project files.
Run one file directly with ruby while developing. Full suites usually run through rake later.
ruby -Itest test/test_math.rb
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
Describe blocks
describe groups tests under a readable label, and it blocks name single behaviors. Readers see sentences instead of method names.
Assertions work the same inside, so teams mix both styles in one suite.
require "minitest/autorun"
describe "calculator" do
it "adds two numbers" do
assert_equal 4, 2 + 2
end
end
Red green refactor
Write a failing test first and watch it go red. Then write the smallest code that turns it green.
Refactor with green tests guarding you: clean the code without changing behavior, and rerun after each step.
def double(n)
n * 2
end
Next: Debugging
Article author: Arthur Isaev