TExcelTAD
Home › Ruby › Ruby Testing with Minitest

Ruby Testing with Minitest

Ruby developers write a lot of automated tests. Because Ruby is dynamic, tests are the main safety net that catches typos, wrong return values and broken edge cases before users do. Minitest is the testing library bundled with Ruby (and the default in Rails). It is small, fast and uses plain Ruby classes and methods.

A first test file

A test is a class that inherits from Minitest::Test. Every method whose name starts with test_ is one test. Inside, assertions check that values are what you expect:

ruby
# test/calculator_test.rb
require "minitest/autorun"
require_relative "../lib/calculator"

class CalculatorTest < Minitest::Test
  def test_add
    assert_equal 5, Calculator.add(2, 3)
  end

  def test_divide_by_zero
    assert_raises(ZeroDivisionError) { Calculator.divide(1, 0) }
  end
end

require "minitest/autorun" runs all test classes when the file finishes loading. Running it in a terminal:

bash · try it yourself
ruby test/calculator_test.rb
Run options: --seed 21894

# Running:

..

Finished in 0.000611s, 3273.3224 runs/s, 3273.3224 assertions/s.

2 runs, 2 assertions, 0 failures, 0 errors, 0 skips

Each . is a passing test. Minitest runs tests in a random order (the seed) to expose tests that accidentally depend on each other.

Running tests in the playground

The automatic runner prints timings and a random seed, which change on every run. To get stable output in the playground, the examples below use a tiny helper that runs each test method in alphabetical order and prints PASS / FAIL / ERROR — the assertions themselves are real Minitest. (The helper is repeated in each example so every playground runs on its own.)

ruby · try it yourself
require "minitest"
Minitest.seed = 1
Encoding.default_external = Encoding::UTF_8  # keeps failure messages short

# Runs every test_ method in alphabetical order and prints one line per test.
def run_tests(test_class)
  test_class.runnable_methods.sort.each do |name|
    result = test_class.new(name).run
    status = result.passed? ? "PASS" : (result.error? ? "ERROR" : "FAIL")
    puts "#{status}  #{name}"
    result.failures.each do |f|
      detail = f.is_a?(Minitest::UnexpectedError) ? "#{f.error.class}: #{f.error.message}" : f.message.lines.map(&:strip).join(" ")
      puts "      #{detail}"
    end
  end
end

class Calculator
  def self.add(a, b) = a + b
  def self.divide(a, b) = a / b
end

class CalculatorTest < Minitest::Test
  def test_add
    assert_equal 5, Calculator.add(2, 3)
  end

  def test_add_negative
    assert_equal(-1, Calculator.add(2, -3))
  end

  def test_divide_by_zero
    assert_raises(ZeroDivisionError) { Calculator.divide(1, 0) }
  end

  def test_divide_floats
    assert_in_delta 0.333, Calculator.divide(1.0, 3), 0.001
  end
end

run_tests(CalculatorTest)
PASS  test_add
PASS  test_add_negative
PASS  test_divide_by_zero
PASS  test_divide_floats

When a test fails

A failing assertion tells you what was expected and what actually happened:

ruby · try it yourself
require "minitest"
Minitest.seed = 1
Encoding.default_external = Encoding::UTF_8  # keeps failure messages short

# Runs every test_ method in alphabetical order and prints one line per test.
def run_tests(test_class)
  test_class.runnable_methods.sort.each do |name|
    result = test_class.new(name).run
    status = result.passed? ? "PASS" : (result.error? ? "ERROR" : "FAIL")
    puts "#{status}  #{name}"
    result.failures.each do |f|
      detail = f.is_a?(Minitest::UnexpectedError) ? "#{f.error.class}: #{f.error.message}" : f.message.lines.map(&:strip).join(" ")
      puts "      #{detail}"
    end
  end
end

def slugify(title)
  title.downcase.gsub(" ", "-")
end

class SlugifyTest < Minitest::Test
  def test_simple
    assert_equal "hello-world", slugify("Hello World")
  end

  def test_punctuation
    assert_equal "ruby-is-fun", slugify("Ruby is fun!")
  end

  def test_nil_input
    assert_equal "", slugify(nil)
  end
end

run_tests(SlugifyTest)
ERROR  test_nil_input
      NoMethodError: undefined method 'downcase' for nil
FAIL  test_punctuation
      Expected: "ruby-is-fun" Actual: "ruby-is-fun!"
PASS  test_simple

Two of these tests reveal real bugs: punctuation isn't removed, and nil input crashes with an error (shown as ERROR, not FAIL). Fixing slugify until everything passes is exactly the test-driven workflow:

ruby · try it yourself
require "minitest"
Minitest.seed = 1
Encoding.default_external = Encoding::UTF_8  # keeps failure messages short

# Runs every test_ method in alphabetical order and prints one line per test.
def run_tests(test_class)
  test_class.runnable_methods.sort.each do |name|
    result = test_class.new(name).run
    status = result.passed? ? "PASS" : (result.error? ? "ERROR" : "FAIL")
    puts "#{status}  #{name}"
    result.failures.each do |f|
      detail = f.is_a?(Minitest::UnexpectedError) ? "#{f.error.class}: #{f.error.message}" : f.message.lines.map(&:strip).join(" ")
      puts "      #{detail}"
    end
  end
end

def slugify(title)
  title.to_s.downcase.gsub(/[^a-z0-9\s-]/, "").split.join("-")
end

class SlugifyTest < Minitest::Test
  def test_simple = assert_equal("hello-world", slugify("Hello World"))
  def test_punctuation = assert_equal("ruby-is-fun", slugify("Ruby is fun!"))
  def test_nil_input = assert_equal("", slugify(nil))
end

run_tests(SlugifyTest)
PASS  test_nil_input
PASS  test_punctuation
PASS  test_simple

Common assertions

Assertion Passes when
assert value value is truthy
refute value value is falsy
assert_equal expected, actual expected == actual
assert_nil value value is nil
assert_includes collection, item collection includes item
assert_in_delta expected, actual, delta floats are close enough
assert_match /regex/, string the regex matches
assert_instance_of Class, obj exact class
assert_raises(Error) { ... } the block raises that error
assert_empty collection collection is empty

Every assert_* has a refute_* opposite (refute_equal, refute_nil, …). Note the order: expected first, actual second — the failure message depends on it.

setup and teardown

setup runs before each test, teardown after each. Use them to build fresh objects so tests never share state:

ruby · try it yourself
require "minitest"
Minitest.seed = 1
Encoding.default_external = Encoding::UTF_8  # keeps failure messages short

# Runs every test_ method in alphabetical order and prints one line per test.
def run_tests(test_class)
  test_class.runnable_methods.sort.each do |name|
    result = test_class.new(name).run
    status = result.passed? ? "PASS" : (result.error? ? "ERROR" : "FAIL")
    puts "#{status}  #{name}"
    result.failures.each do |f|
      detail = f.is_a?(Minitest::UnexpectedError) ? "#{f.error.class}: #{f.error.message}" : f.message.lines.map(&:strip).join(" ")
      puts "      #{detail}"
    end
  end
end

class Cart
  attr_reader :items
  def initialize = @items = []
  def add(name, price) = @items << [name, price]
  def total = @items.sum { |_, p| p }
end

class CartTest < Minitest::Test
  def setup
    @cart = Cart.new
    @cart.add("pen", 2)
  end

  def test_starts_with_one_item
    assert_equal 1, @cart.items.size
  end

  def test_total_adds_prices
    @cart.add("book", 10)
    assert_equal 12, @cart.total
  end

  def test_items_include_pen
    assert_includes @cart.items.map(&:first), "pen"
  end
end

run_tests(CartTest)
PASS  test_items_include_pen
PASS  test_starts_with_one_item
PASS  test_total_adds_prices

test_total_adds_prices adds a book, but test_starts_with_one_item still sees one item: each test gets a brand-new cart from setup.

Spec style

Minitest also offers an RSpec-like "spec" syntax if you prefer describing behaviour:

ruby
require "minitest/autorun"

describe Cart do
  before { @cart = Cart.new }

  it "starts empty" do
    _(@cart.items).must_be_empty
  end

  it "sums prices" do
    @cart.add("pen", 2)
    _(@cart.total).must_equal 2
  end
end

Running a test suite

In a real project, tests live in a test/ folder and are run with Rake:

bash · try it yourself
bundle exec rake test
Run options: --seed 4471

# Running:

.........F..

Failure:
CartTest#test_discount [test/cart_test.rb:31]:
Expected: 18.0
  Actual: 20.0

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

Tip: Write a failing test first, then the code that makes it pass, then tidy up ("red → green → refactor"). Tests written this way document exactly what your code is supposed to do.

Test yourself

Which methods does Minitest run as tests?

  1. All public methods
  2. Methods whose names start with test_
  3. Methods marked with @test
  4. Only run

What is the correct argument order for assert_equal?

  1. actual, expected
  2. expected, actual
  3. Either order
  4. message, expected, actual

When does setup run?

  1. Once before all tests
  2. Before each test
  3. After each test
  4. Only when a test fails