Testing with Minitest

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

Run options: --seed 12345

# Running:

.

Finished in 0.0016s, 625.0000 runs/s, 625.0000 assertions/s.

1 runs, 1 assertions, 0 failures, 0 errors, 0 skips

The seed and the timings change on every run; the last line is the summary that matters. A failure prints the failing test, the expected value and the stack of the assertion instead of the dot.

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: Minitest assertions

Article author: Arthur Isaev