Thuta Learning
Ruby
AdvancedProgrammingBeginner

Testing with Minitest

RubyLesson 2740 min

What you'll walk away with

  • Write a Minitest::Test class with methods that start with test_
  • Explain why assert_equal takes the expected value first and the actual value second
  • Use assert_raises, setup and teardown to check error cases and keep state clean
  • Read a report with dots, F, E and a seed, and explain why tests must not depend on each other

Explain it simply

Explain it simply

A test is a tiny program that checks whether your code does what you claim. You write "given this input, this answer must come out" and let the computer check it every time. Unlike eyeballing printed output, the check never gets forgotten, and the computer can run thousands of them in a second.

Minitest is the test library that ships with Ruby, so there is nothing to install. It has no heavy DSL: tests are ordinary classes and methods, so if you already know Ruby you can start writing tests within minutes.

Problem → Why → Solution

The problem: checking by eye misses things

You write an average method and try it with a few numbers using puts. The first output looks right, so you call it done. But two bugs hide in the code below: the average of [1, 2] should be 1.5 and integer division gives 1, and an empty array crashes with ZeroDivisionError.

Checking by eye only covers the examples you happened to try, and after every change you forget to re-run all of them. That is how an old feature breaks and a user finds out before you do.

average.rb
def average(numbers) = numbers.sum / numbers.size

puts average([2, 4, 6])   # 4   looks right
puts average([1, 2])      # 1   should be 1.5: integer division
puts average([])          # ZeroDivisionError: divided by 0

Why do you need tests?

A test turns "it seems right" into a fact the computer checks. Write the normal, empty, boundary and error cases once, and they are re-checked after every change, and a bug you fixed cannot quietly come back.

Core concept: test classes, assertions and the report

A Minitest file has three parts. First, require "minitest/autorun" loads the library and arranges for every test to run when the file ends. Second, a class that inherits from Minitest::Test; every method whose name starts with test_ is one test. Third, assertions inside those methods: assert_equal expected, actual, assert_raises(SomeError) { ... }, assert, assert_nil and friends. An assertion that holds does nothing; one that does not raises Minitest::Assertion and the test is marked as failed.

Every test runs in a brand-new instance of the class, setup runs just before each test and teardown just after, so every test starts from a clean state. Minitest also runs tests in random order and announces a seed at the top of the report (--seed 42 replays that order). This is deliberate: a test that only passes after another test has run has a hidden dependency, and random order exposes it quickly.

To read the report: a passing test prints a dot, a failed assertion prints F, and an unexpected exception, such as a NoMethodError from a typo, prints E. Failures and errors are listed below with the test name, the line and, for assert_equal, the expected and actual values. The last line counts runs, assertions, failures, errors and skips. The seed and the timing line change on every run, so never copy them into expected output.

assert_equal takes the expected value first and the actual value second. Nothing stops you from swapping them, and the test still passes or fails correctly, but a failure message then labels the numbers the wrong way round and sends you looking in the wrong direction.

AssertionPasses when
assert_equal expected, actualexpected == actual
assert_nil valuevalue is nil
assert_includes list, itemlist.include?(item)
assert_in_delta expected, actualtwo floats are within delta of each other (default 0.001)
assert_raises(Error) { ... }the block raises Error; it returns the exception
refute_equal, refute_nil ...the opposite of the matching assert_
Mental model: write, run, read, fix
  1. Write a test: setup, act, assert
  2. Each test runs in a fresh object
  3. Dot passes, F fails, E is an error
  4. Fix the code and run again

Each test must stand alone, and the result must be the same in whatever order they run.

General pattern

ruby
require "minitest/autorun"

class NameTest < Minitest::Test
  def setup
    @subject = Thing.new
  end

  def test_describes_expected_behaviour
    assert_equal expected, @subject.action
    assert_raises(SomeError) { @subject.bad_action }
  end
end

The class is named XxxTest and its methods start with test_. setup runs before each test and prepares instance variables such as @subject. Name each method like a sentence about the behaviour it checks.

Example: testing a shopping cart

The file has a Cart class and three tests: an empty cart, adding prices, and rejecting a price of 0. In your own files you would write require "minitest/autorun", and the tests would run automatically when the file ends. In this lesson's example we start the run ourselves, so we can pin the seed to 42 and drop the "Finished in" timing line that changes on every run; that keeps the output identical every time.

cart_test.rb
require "minitest"
require "stringio"

class Cart
  def initialize
    @items = []
  end

  def add(name, cents)
    raise ArgumentError, "price must be positive" unless cents.positive?

    @items << [name, cents]
    self
  end

  def size = @items.size
  def total_cents = @items.sum { |_, cents| cents }
end

class CartTest < Minitest::Test
  def setup
    @cart = Cart.new
  end

  def test_new_cart_is_empty
    assert_equal 0, @cart.size
    assert_equal 0, @cart.total_cents
  end

  def test_total_adds_prices
    @cart.add("pen", 150).add("book", 1250)
    assert_equal 1400, @cart.total_cents
  end

  def test_rejects_zero_price
    error = assert_raises(ArgumentError) { @cart.add("free", 0) }
    assert_equal "price must be positive", error.message
  end
end

# Start the run ourselves so the seed is fixed and the timing line can be removed
def run_quietly(seed)
  captured = StringIO.new
  original = $stdout
  $stdout = captured
  begin
    Minitest.run(["--seed", seed.to_s])
  ensure
    $stdout = original
  end
  captured.string.sub(/^Finished in .*\n\n/, "")
end

puts run_quietly(42)

Code breakdown

  1. Test classclass CartTest < Minitest::Test

    Inheriting from Minitest::Test is how Minitest recognises this class as tests. Every method inside whose name starts with test_ is one test.

  2. setup@cart = Cart.new

    setup runs before each test, so every test gets a brand-new empty cart. Items added by one test cannot affect another.

  3. Expected firstassert_equal 1400, @cart.total_cents

    The first argument, 1400, is the value you expect and the second is what the code returns. 150 + 1250 is 1400, so this assertion passes.

  4. assert_raiseserror = assert_raises(ArgumentError) { @cart.add("free", 0) }

    The code in the block must raise ArgumentError, or the test fails. The exception it returns can be stored and its message checked as well.

  5. Fixed seedMinitest.run(["--seed", seed.to_s])

    This line runs every test with seed 42. The same seed gives the same random order, so nothing varies between runs. In your own files autorun does the job.

  6. Dropping the timingcaptured.string.sub(/^Finished in .*\n\n/, "")

    The output is captured in a StringIO and the "Finished in ..." line is cut out. Everything else (seed, dots, counts) is Minitest's real output.

You should see
Run options: --seed 42

# Running:

...

3 runs, 5 assertions, 0 failures, 0 errors, 0 skips

Reading a real report

Running your own file with ruby cart_test.rb makes autorun print a report like the ones below. These are real runs; in the first, the expected value in test_total_adds_prices was deliberately written as 1500, and in the second a method name in test_new_cart_is_empty was deliberately misspelt as totl_cents. The seed, the "Finished in" line and the order of dots and F differ on every run, so yours will not match exactly, but the shape is the same.

a failing run (sample from Ruby 4.0.9, varies every run)
Run options: --seed 51234

# Running:

..F

Finished in 0.001178s, 2547.3380 runs/s, 4245.5634 assertions/s.

  1) Failure:
CartTest#test_total_adds_prices [cart_test.rb:31]:
Expected: 1500
  Actual: 1400

3 runs, 5 assertions, 1 failures, 0 errors, 0 skips
an error run (sample from Ruby 4.0.9, varies every run)
Run options: --seed 7

# Running:

..E

Finished in 0.000889s, 3375.7174 runs/s, 4500.9565 assertions/s.

  1) Error:
CartTest#test_new_cart_is_empty:
NoMethodError: undefined method 'totl_cents' for an instance of Cart
    cart_test.rb:26:in 'CartTest#test_new_cart_is_empty'

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

Tell Failure and Error apart. A Failure means an assertion said "not true": the code ran and gave a wrong answer. An Error means an unexpected exception was raised while the test ran, such as the misspelt method totl_cents. An Error stops that test on the spot, so any later assertions in it are never checked.

Expected first: reading the failure message

The script below calls assertions directly, without a test class, and prints their messages. The Probe class includes Minitest::Assertions, which is why assertions work outside a test class. total([2, 3, 1]) is 6. We expected 5, so the first message, "Expected: 5, Actual: 6", is correct. In the second call the arguments are swapped, and the message says "Expected: 6, Actual: 5", which reads as if the code were wrong in the opposite direction. And do not compare floats with assert_equal: 0.1 + 0.2 is 0.30000000000000004, so use assert_in_delta.

messages.rb
require "minitest"

# A tiny object that can run assertions outside a test class
class Probe
  include Minitest::Assertions
  attr_accessor :assertions

  def initialize = @assertions = 0
end

def total(prices) = prices.sum

def message_for
  yield
  "(passed)"
rescue Minitest::Assertion => e
  e.message
end

probe = Probe.new
puts "Right order:"
puts message_for { probe.assert_equal 5, total([2, 3, 1]) }
puts "Swapped:"
puts message_for { probe.assert_equal total([2, 3, 1]), 5 }
puts "Floats:"
puts message_for { probe.assert_equal 0.3, 0.1 + 0.2 }
puts message_for { probe.assert_in_delta 0.3, 0.1 + 0.2 }
puts "assert_raises:"
puts message_for { probe.assert_raises(ArgumentError) { 1 + 1 } }
output (Minitest 6.0.0 on Ruby 4.0.9)
Right order:
Expected: 5
  Actual: 6
Swapped:
Expected: 6
  Actual: 5
Floats:
Expected: 0.3
  Actual: 0.30000000000000004
(passed)
assert_raises:
ArgumentError expected but nothing was raised.

Test style and spec style

Minitest offers two ways to write tests. The test style used so far is classes, methods and assert_. The spec style (require "minitest/spec") resembles RSpec, with describe, it, before and _(value).must_equal. Both use the same runner and report and only differ in how you write them, so pick whichever your team prefers. In spec style, must_equal also takes the expected value as its argument (_(actual).must_equal expected), so keep the sides straight.

Test styleSpec style
class StackTest < Minitest::Testdescribe Stack do
def setupbefore do
def test_pops_last_itemit "pops the last item" do
assert_equal 2, stack.pop_(stack.pop).must_equal 2
assert_raises(IndexError) { ... }_ { ... }.must_raise IndexError
stack_spec.rb
require "minitest/spec"
require "stringio"

class Stack
  def initialize = @items = []
  def push(item) = @items.push(item) && self
  def pop = @items.pop || raise(IndexError, "stack is empty")
  def empty? = @items.empty?
  def size = @items.size
end

describe Stack do
  before do
    @stack = Stack.new
  end

  it "starts empty" do
    _(@stack.empty?).must_equal true
  end

  it "pops the last pushed item" do
    @stack.push(1).push(2)
    _(@stack.pop).must_equal 2
    _(@stack.size).must_equal 1
  end

  it "raises when popping an empty stack" do
    error = _ { @stack.pop }.must_raise IndexError
    _(error.message).must_equal "stack is empty"
  end
end

captured = StringIO.new
original = $stdout
$stdout = captured
begin
  Minitest.run(["--seed", "7"])
ensure
  $stdout = original
end
puts captured.string.lines.last   # 3 runs, 5 assertions, 0 failures, 0 errors, 0 skips

Running tests from the command line

In a real project you keep test files in a test/ folder and run them by calling ruby directly or with rake test. --seed replays a failing order, and -n runs a single test or the tests whose names match. Minitest 6's help text lists that option as -i/--include, but -n still works. In a Rakefile, one line, Minitest::TestTask.create, defines the rake test task.

bash
ruby test/cart_test.rb                           # run one file
ruby test/cart_test.rb --seed 42                 # the same order every time
ruby test/cart_test.rb -n test_rejects_zero_price   # one test by name
ruby test/cart_test.rb -n /rejects/              # tests whose name matches
rake test                                        # every file in test/ (needs a Rakefile)
Rakefile
require "minitest/test_task"

Minitest::TestTask.create   # defines the "rake test" task

In real projects

Where this shows up in real projects

Rails creates a test/ folder for new apps and uses Minitest as its default test framework. Many Ruby gems ship with their own tests too. Teams run rake test in CI on every push and refuse to merge when it fails. That habit takes the fear out of changing code: after a refactor, passing tests are your evidence that behaviour did not change.

When you find a bug, first write a test that reproduces it, watch it fail, and only then fix the code. That regression test guards against the bug returning forever. You can start new features the same way: write the test, watch it fail, write the code, make it pass. That is called TDD. Other frameworks such as RSpec exist, but the basic ideas of assertions, setup and random order are the same.

Common mistakes

Common mistakes

1. Swapping the two arguments of assert_equal

Writing the actual value first, assert_equal total(items), 5, gives a failure that reads "Expected: 6, Actual: 5". You then misremember which value came from the code and can look in the wrong place for a long time. Always put the expected value first and the code's result second.

2. Sharing state between tests

If tests write to a class constant, a @@variable or a global, one test changes the outcome of another, and under random order the suite passes one run and fails the next. See the code below: building the state as an instance variable in setup fixes it.

3. A method name that does not start with test_

A method written as def check_total ... end is not seen as a test by Minitest. The report says "0 runs, 0 assertions, 0 failures", which looks like success but checked nothing. Always glance at the number of runs.

4. Comparing floats with assert_equal

0.1 + 0.2 is 0.30000000000000004, so assert_equal 0.3, 0.1 + 0.2 fails. That is normal behaviour of binary floating point. Use assert_in_delta, or store money as integers such as cents.

independent_tests.rb
require "minitest"
require "stringio"

class LeakyTest < Minitest::Test
  LOG = []          # one array shared by every test

  def test_first_entry
    LOG << :a
    assert_equal [:a], LOG
  end

  def test_second_entry
    LOG << :b
    assert_equal [:b], LOG
  end
end

class FixedTest < Minitest::Test
  def setup
    @log = []       # a fresh array before every test
  end

  def test_first_entry
    @log << :a
    assert_equal [:a], @log
  end

  def test_second_entry
    @log << :b
    assert_equal [:b], @log
  end
end

def summary_for(pattern)
  captured = StringIO.new
  original = $stdout
  $stdout = captured
  begin
    Minitest.run(["--seed", "1", "-n", pattern])
  ensure
    $stdout = original
  end
  captured.string.lines.last.strip
end

puts "LeakyTest: #{summary_for("/LeakyTest/")}"
puts "FixedTest: #{summary_for("/FixedTest/")}"
output (Minitest 6.0.0 on Ruby 4.0.9)
LeakyTest: 2 runs, 2 assertions, 1 failures, 0 errors, 0 skips
FixedTest: 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

Whatever seed you use, LeakyTest has exactly one failure, because whichever test runs first fills LOG and the second one meets a LOG that is already full. Which test fails depends on the seed: while writing this lesson, seed 1 made test_second_entry fail and seed 2 made test_first_entry fail.

Best practices

Best practices

  • Test one behaviour per test and name it like a sentence about what it checks (test_rejects_zero_price).
  • Do not test only the happy path; test empty, boundary, nil and error cases too.
  • Build each test's data in setup and never touch global state; when you need files use Dir.mktmpdir.
  • When you fix a bug, first write a test that reproduces it and watch it fail.

Mini challenge

Mini challenge: test an Inventory

Write an Inventory class and four Minitest tests for it, then run them with a fixed seed and print the report without the timing line.

  • Inventory has add(sku, quantity), remove(sku, quantity) and quantity(sku); an unknown sku has quantity 0
  • Removing more than is in stock raises OutOfStock with a message like "only 1 of pen left"
  • The four tests cover an empty quantity, adding up, removing, and OutOfStock checked with assert_raises
  • A new Inventory is built in setup, and no test depends on another
inventory_test.rb
require "minitest"
require "stringio"

# TODO: class OutOfStock < StandardError

# TODO: class Inventory with add, remove (raise OutOfStock when short) and quantity
#       hint: Hash.new(0) gives every unknown sku a quantity of 0

class InventoryTest < Minitest::Test
  # TODO: setup builds a fresh Inventory

  # TODO: four tests, each starting with test_
  #       use assert_equal expected, actual and assert_raises(OutOfStock) { ... }
end

def run_quietly(seed)
  captured = StringIO.new
  original = $stdout
  $stdout = captured
  begin
    Minitest.run(["--seed", seed.to_s])
  ensure
    $stdout = original
  end
  captured.string.sub(/^Finished in .*\n\n/, "")
end

# TODO: print run_quietly(1)

Expected: All four tests pass: Run options: --seed 1 # Running: .... 4 runs, 6 assertions, 0 failures, 0 errors, 0 skips

Show hint

In remove, raise when quantity > @stock[sku]. assert_raises returns the exception, so you can check error.message afterwards, and then check that the stock did not change.

Show solution
inventory_test.rb
require "minitest"
require "stringio"

class OutOfStock < StandardError; end

class Inventory
  def initialize
    @stock = Hash.new(0)
  end

  def add(sku, quantity)
    @stock[sku] += quantity
  end

  def remove(sku, quantity)
    raise OutOfStock, "only #{@stock[sku]} of #{sku} left" if quantity > @stock[sku]

    @stock[sku] -= quantity
  end

  def quantity(sku) = @stock[sku]
end

class InventoryTest < Minitest::Test
  def setup
    @inventory = Inventory.new
  end

  def test_unknown_sku_has_zero_quantity
    assert_equal 0, @inventory.quantity("pen")
  end

  def test_add_accumulates
    @inventory.add("pen", 5)
    @inventory.add("pen", 3)
    assert_equal 8, @inventory.quantity("pen")
  end

  def test_remove_reduces_stock
    @inventory.add("pen", 5)
    @inventory.remove("pen", 2)
    assert_equal 3, @inventory.quantity("pen")
  end

  def test_remove_too_many_raises
    @inventory.add("pen", 1)
    error = assert_raises(OutOfStock) { @inventory.remove("pen", 2) }
    assert_equal "only 1 of pen left", error.message
    assert_equal 1, @inventory.quantity("pen")
  end
end

def run_quietly(seed)
  captured = StringIO.new
  original = $stdout
  $stdout = captured
  begin
    Minitest.run(["--seed", seed.to_s])
  ensure
    $stdout = original
  end
  captured.string.sub(/^Finished in .*\n\n/, "")
end

puts run_quietly(1)

Quick quiz 1 / 3

total([2, 3, 1]) returns 6. If assert_equal total([2, 3, 1]), 5 fails, what does the message show?

Quick quiz 2 / 3

What does an E in the progress line mean?

Quick quiz 3 / 3

Why does Minitest run tests in random order?

What to remember

  • A Minitest test is a method starting with test_ in a class that inherits Minitest::Test; a failed assertion is a failure.
  • Write assert_equal expected, actual in that order; swapped, the failure message labels the values backwards.
  • setup and teardown give each test a clean state, and random order with a seed exposes tests that depend on each other.
  • In the report a dot passes, F is a failure and E is an error; the seed and the timing line change every run.

Minitest Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Testing with Minitest | Thuta Learning