Parameterized tests

suggest change

A parameterized (table-driven, data-driven) test runs the same test logic against a list of inputs and expected outputs. Instead of copy-pasting five nearly identical test methods, you write the check once and keep the cases in a table:

input expected
"Hello World" "hello-world"
" trim me " "trim-me"
"Crème Brûlée" "creme-brulee"

Ruby test frameworks don't need annotations like JUnit's @ParameterizedTest. Test classes and describe blocks are ordinary Ruby code, so a loop that defines tests is all it takes. This article shows how to do it well in Minitest, RSpec and test-unit, and the pitfalls to avoid.

The examples test this small module:

# slug.rb
module Slug
  module_function

  def call(text)
    text.unicode_normalize(:nfkd)
        .gsub(/\p{Mn}/, "")   # drop combining accents
        .downcase
        .gsub(/[^a-z0-9]+/, "-")
        .delete_prefix("-")
        .delete_suffix("-")
  end
end

The naive approach: a loop inside one test

The simplest version iterates over the cases inside a single test method:

require "minitest/autorun"
require_relative "slug"

class SlugLoopTest < Minitest::Test
  def test_slugs
    [
      ["Hello World",     "hello-world"],
      ["  trim me  ",     "trim-me"],
      ["Crème Brûlée",    "creme-brulee"],
      ["C++ & Ruby",      "c-plus-plus-ruby"],
      ["already-a-slug",  "already-a-slug!"],
    ].each do |input, expected|
      assert_equal expected, Slug.call(input), "for input #{input.inspect}"
    end
  end
end
  1) Failure:
SlugLoopTest#test_slugs [slug_loop_test.rb:13]:
for input "C++ & Ruby".
Expected: "c-plus-plus-ruby"
  Actual: "c-ruby"

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

It works, but it has three problems:

The fix is to turn each row into its own test.

Minitest: one test method per case

A Minitest test is any public method whose name starts with test_. Class bodies run code, so you can generate those methods with define_method:

require "minitest/autorun"
require_relative "slug"

class SlugTest < Minitest::Test
  CASES = {
    "Hello World"    => "hello-world",
    "  trim me  "    => "trim-me",
    "Crème Brûlée"   => "creme-brulee",
    "C++ & Ruby"     => "c-plus-plus-ruby",
    "already-a-slug" => "already-a-slug",
  }

  CASES.each_with_index do |(input, expected), i|
    define_method("test_slug_#{i}_#{input}") do
      assert_equal expected, Slug.call(input)
    end
  end
end
$ ruby slug_test.rb -v
SlugTest#test_slug_2_Crème Brûlée = 0.01 s = .
SlugTest#test_slug_1_  trim me   = 0.00 s = .
SlugTest#test_slug_4_already-a-slug = 0.00 s = .
SlugTest#test_slug_0_Hello World = 0.00 s = .
SlugTest#test_slug_3_C++ & Ruby = 0.00 s = F

  1) Failure:
SlugTest#test_slug_3_C++ & Ruby [slug_test.rb:15]:
Expected: "c-plus-plus-ruby"
  Actual: "c-ruby"

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

Now every case runs, the failure is named after its input, and Minitest shuffles the cases like any other tests.

Some details:

A reusable parameterize helper

With more than a couple of tables, a small class macro reads better than raw define_method. This one gives each case a label, passes its values to the block as arguments, and refuses duplicate labels:

# param.rb
module Parameterized
  def parameterize(name, cases, &body)
    cases.each do |label, *args|
      method_name = "test_#{name}[#{label}]"
      if method_defined?(method_name)
        raise ArgumentError, "duplicate test case: #{method_name}"
      end
      define_method(method_name) { instance_exec(*args, &body) }
    end
  end
end

instance_exec runs the block with self set to the test instance, so assert_equal and the other assertions work inside it:

require "minitest/autorun"
require_relative "param"

def leap_year?(year)
  (year % 4).zero? && (!(year % 100).zero? || (year % 400).zero?)
end

class LeapYearTest < Minitest::Test
  extend Parameterized

  parameterize "leap_year", [
    ["divisible by 4",     2024, true],
    ["not divisible by 4", 2023, false],
    ["century",            1900, false],
    ["divisible by 400",   2000, true],
  ] do |year, expected|
    assert_equal expected, leap_year?(year)
  end

  parameterize "integer_parsing", [
    ["plain",      "42",    42],
    ["underscore", "1_000", 1000],
    ["hex",        "0x1F",  31],
  ] do |input, expected|
    assert_equal expected, Integer(input)
  end
end
LeapYearTest#test_leap_year[divisible by 400] = 0.00 s = .
LeapYearTest#test_integer_parsing[plain] = 0.00 s = .
LeapYearTest#test_leap_year[century] = 0.00 s = .
LeapYearTest#test_integer_parsing[underscore] = 0.00 s = .
LeapYearTest#test_leap_year[not divisible by 4] = 0.00 s = .
LeapYearTest#test_leap_year[divisible by 4] = 0.00 s = .
LeapYearTest#test_integer_parsing[hex] = 0.00 s = .

7 runs, 7 assertions, 0 failures, 0 errors, 0 skips

The duplicate check matters. Plain define_method silently replaces a method with the same name, so a copy-pasted row with an unchanged label makes a case disappear. With ruby -w you get only a warning:

dup_test.rb:5: warning: method redefined; discarding old test_a
dup_test.rb:5: warning: previous definition of test_a was here

The helper raises instead, when the file loads:

param.rb:7:in 'block in Parameterized#parameterize': duplicate test case: test_x[a] (ArgumentError)

Running a single case

Since each case is a real test method, Minitest's -n (--name) filter selects cases by name or by regexp:

$ ruby leap_year_test.rb -n "/century/"
Run options: -n /century/ --seed 22470

# Running:

.

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

With rake test, pass it through: rake test TESTOPTS="-n /century/".

Tables with expected exceptions

Error cases can share a table with success cases. Use the exception class as the expected value and branch on it:

require "minitest/autorun"

class IntegerParsingTest < Minitest::Test
  CASES = [
    # input,  expected value or exception class
    ["42",    42],
    ["-7",    -7],
    ["0b101", 5],
    ["4.2",   ArgumentError],
    ["",      ArgumentError],
    [nil,     TypeError],
  ]

  CASES.each do |input, expected|
    define_method("test_Integer(#{input.inspect})") do
      if expected.is_a?(Class) && expected <= Exception
        assert_raises(expected) { Integer(input) }
      else
        assert_equal expected, Integer(input)
      end
    end
  end
end
IntegerParsingTest#test_Integer("42") = 0.00 s = .
IntegerParsingTest#test_Integer("-7") = 0.00 s = .
IntegerParsingTest#test_Integer("4.2") = 0.00 s = .
IntegerParsingTest#test_Integer("0b101") = 0.00 s = .
IntegerParsingTest#test_Integer(nil) = 0.00 s = .
IntegerParsingTest#test_Integer("") = 0.00 s = .

6 runs, 6 assertions, 0 failures, 0 errors, 0 skips

This is fine for one or two error rows. If the success and error rows need different checks, split them into two tables. A test full of if branches is hard to read.

Named fields with Data

Positional arrays get hard to read past three columns. Data (Ruby 3.2+) gives each case named, immutable fields, and a missing field raises an error:

require "minitest/autorun"

Case = Data.define(:name, :price, :qty, :total)

class TotalTest < Minitest::Test
  CASES = [
    Case.new(name: "single item",   price: 10.0, qty: 1, total: 10.0),
    Case.new(name: "several items", price: 2.5,  qty: 4, total: 10.0),
    Case.new(name: "zero quantity", price: 99.0, qty: 0, total: 0.0),
  ]

  CASES.each do |c|
    define_method("test_total[#{c.name}]") do
      assert_equal c.total, c.price * c.qty
    end
  end
end
TotalTest#test_total[zero quantity] = 0.00 s = .
TotalTest#test_total[single item] = 0.00 s = .
TotalTest#test_total[several items] = 0.00 s = .

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

Hashes also work, with pattern matching to unpack them. The RSpec example below does this.

RSpec: generating examples in a loop

describe and context blocks are plain Ruby too. Calling it inside each defines one example per row. Put the input in the description so the output reads like a spec:

require_relative "slug"

RSpec.describe Slug do
  {
    "Hello World"  => "hello-world",
    "  trim me  "  => "trim-me",
    "Crème Brûlée" => "creme-brulee",
    "C++ & Ruby"   => "c-plus-plus-ruby",
  }.each do |input, expected|
    it "turns #{input.inspect} into #{expected.inspect}" do
      expect(Slug.call(input)).to eq(expected)
    end
  end
end
$ rspec slug_spec.rb --format documentation
Slug
  turns "Hello World" into "hello-world"
  turns "  trim me  " into "trim-me"
  turns "Crème Brûlée" into "creme-brulee"
  turns "C++ & Ruby" into "c-plus-plus-ruby" (FAILED - 1)

Failures:

  1) Slug turns "C++ & Ruby" into "c-plus-plus-ruby"
     Failure/Error: expect(Slug.call(input)).to eq(expected)

       expected: "c-plus-plus-ruby"
            got: "c-ruby"

       (compared using ==)
     # ./slug_spec.rb:11:in 'block (3 levels) in <top (required)>'

4 examples, 1 failure

Failed examples:

rspec './slug_spec.rb[1:4]' # Slug turns "C++ & Ruby" into "c-plus-plus-ruby"

Generated examples have no unique line number, so RSpec gives a re-run command with an example id ([1:4]) instead. You can also select a case by its description with -e:

$ rspec slug_spec.rb -e "Crème"
Run options: include {full_description: /Crème/}
.

1 example, 0 failures

A context per row

When each case needs its own subject, let or several examples, generate a context for each row. Rows as hashes are easy to unpack with rightward pattern matching:

require "date"

RSpec.describe "Date.leap?" do
  [
    {year: 2024, leap: true,  why: "divisible by 4"},
    {year: 2023, leap: false, why: "not divisible by 4"},
    {year: 1900, leap: false, why: "century not divisible by 400"},
    {year: 2000, leap: true,  why: "divisible by 400"},
  ].each do |row|
    row => {year:, leap:, why:}

    context "#{year} (#{why})" do
      subject { Date.leap?(year) }

      it { is_expected.to eq(leap) }
    end
  end
end
Date.leap?
  2024 (divisible by 4)
    is expected to eq true
  2023 (not divisible by 4)
    is expected to eq false
  1900 (century not divisible by 400)
    is expected to eq false
  2000 (divisible by 400)
    is expected to eq true

4 examples, 0 failures

Don't write each do |year:, leap:, why:|. Since Ruby 3.0 a hash is no longer converted to keyword arguments for a block, and loading the file fails with ArgumentError: missing keywords: :year, :leap, :why.

Shared examples with parameters

To run a whole group of examples against several implementations, use shared_examples. Arguments given to it_behaves_like become the block parameters:

require "set"

RSpec.shared_examples "a collection" do |klass, items|
  subject(:collection) { klass.new(items) }

  it "reports its size" do
    expect(collection.size).to eq(items.size)
  end

  it "includes every item" do
    expect(items).to all(satisfy { |item| collection.include?(item) })
  end

  it "is enumerable" do
    expect(collection).to be_a(Enumerable)
  end
end

RSpec.describe "collections" do
  [[Array, [1, 2, 3]], [Set, [1, 2, 3]]].each do |klass, items|
    describe klass do
      it_behaves_like "a collection", klass, items
    end
  end
end
collections
  Array
    behaves like a collection
      reports its size
      includes every item
      is enumerable
  Set
    behaves like a collection
      reports its size
      includes every item
      is enumerable

6 examples, 0 failures

The describe klass wrapper is needed. Without it both groups are named "behaves like a collection", and you can't tell from a failure which class broke.

One example, all failures: aggregate_failures

Sometimes you want a single example that checks many rows, for instance when the setup is expensive. aggregate_failures keeps going after a failed expectation and reports all failures at the end. This fixes the "stops at the first failure" problem of the naive loop:

RSpec.describe "Integer()" do
  it "parses all supported formats" do
    aggregate_failures do
      {"42" => 42, "0x1F" => 31, "0b101" => 5, "1_000" => 1001, "0o17" => 16}.each do |input, expected|
        expect(Integer(input)).to eq(expected),
          -> { "Integer(#{input.inspect}): expected #{expected}, got #{Integer(input)}" }
      end
    end
  end
end
  1) Integer() parses all supported formats
     Got 2 failures from failure aggregation block.

     1.1) Failure/Error: expect(Integer(input)).to eq(expected), ...
            Integer("1_000"): expected 1001, got 1000

     1.2) Failure/Error: expect(Integer(input)).to eq(expected), ...
            Integer("0o17"): expected 16, got 15

1 example, 1 failure

A custom failure message replaces the default "expected/got" text, so put both values in it. Passing a lambda means the message is only built when the expectation fails.

test-unit: built-in data

test-unit, the xUnit framework bundled with Ruby, supports data-driven tests directly. Each data call adds a labeled case for the next test method, and the method receives the case as its argument:

require "test/unit"
require "date"
require_relative "slug"

class SlugTest < Test::Unit::TestCase
  data("simple",     ["Hello World",  "hello-world"])
  data("whitespace", ["  trim me  ",  "trim-me"])
  data("accents",    ["Crème Brûlée", "creme-brulee"])
  def test_call(data)
    input, expected = data
    assert_equal(expected, Slug.call(input))
  end

  # or all cases at once, as a hash of label => data
  data(
    "symbols" => ["C++ & Ruby", "c-ruby"],
    "slug"    => ["already-a-slug", "already-a-slug"],
  )
  def test_call_hash(data)
    input, expected = data
    assert_equal(expected, Slug.call(input))
  end

  # a symbol key with an array of values builds the cross product
  data(:year, [2000, 2024])
  data(:leap, [true])
  def test_matrix(data)
    assert_equal(data[:leap], Date.leap?(data[:year]))
  end
end
$ ruby slug_test.rb -v
SlugTest:
  test_call[simple]:                         .: (0.012030)
  test_call[whitespace]:                     .: (0.000049)
  test_call[accents]:                        .: (0.000083)
  test_call_hash[symbols]:                   .: (0.000042)
  test_call_hash[slug]:                      .: (0.000040)
  test_matrix[leap: true, year: 2000]:       .: (0.000038)
  test_matrix[leap: true, year: 2024]:       .: (0.000033)

7 tests, 7 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
100% passed

Since Ruby 2.2, test-unit is a bundled gem rather than part of the standard library. Add gem "test-unit" to your Gemfile when you use Bundler.

Loading cases from a file

When the table is large, maintained by non-programmers, or shared with another implementation, keep it in a YAML or JSON file:

# fixtures/slugs.yml
- name: simple
  input: Hello World
  expected: hello-world
- name: accents
  input: Crème Brûlée
  expected: creme-brulee
- name: only symbols
  input: "!!!"
  expected: ""
require "minitest/autorun"
require "yaml"
require_relative "slug"

class SlugFixtureTest < Minitest::Test
  path = File.join(__dir__, "fixtures/slugs.yml")

  YAML.load_file(path, symbolize_names: true).each do |c|
    define_method("test_slug[#{c[:name]}]") do
      assert_equal c[:expected], Slug.call(c[:input])
    end
  end
end
3 runs, 3 assertions, 0 failures, 0 errors, 0 skips

The file is read once, when the class body runs. YAML.load_file uses safe loading (Psych 4+), so the file can only create plain data such as strings, numbers, arrays and hashes, not arbitrary objects.

Combinations with Array#product

To test every combination of several parameters, build the rows with Array#product instead of writing them by hand:

require "minitest/autorun"

def pad(text, width, side)
  case side
  when :left  then text.rjust(width)
  when :right then text.ljust(width)
  when :both  then text.center(width)
  end
end

class PadTest < Minitest::Test
  texts  = ["", "a", "hello"]
  widths = [0, 5, 10]
  sides  = %i[left right both]

  texts.product(widths, sides).each do |text, width, side|
    define_method("test_pad[#{text.inspect}, #{width}, #{side}]") do
      result = pad(text, width, side)
      assert_equal [text.size, width].max, result.size
      assert_includes result, text
    end
  end
end
27 runs, 81 assertions, 0 failures, 0 errors, 0 skips

3 x 3 x 3 = 27 tests from three short lists. The number of combinations grows fast, so check properties that hold for every combination (here, the length and that the text is still there) rather than listing an expected value for each one.

Pitfall: for shares one variable

each creates a new block scope on every iteration, so every closure captures its own values. A for loop doesn't create a new scope. Its variable belongs to the surrounding scope and is reassigned on each pass, so all the generated tests see the last value:

require "minitest/autorun"

class ForPitfallTest < Minitest::Test
  for n in [1, 2, 3]
    define_method("test_positive_#{n}") do
      puts "checking #{n}"
      assert n.positive?
    end
  end
end
ForPitfallTest#test_positive_3 = checking 3
0.00 s = .
ForPitfallTest#test_positive_2 = checking 3
0.00 s = .
ForPitfallTest#test_positive_1 = checking 3
0.00 s = .

The method names are right, because the string is built during the loop. The bodies run later, when n is already 3. So test_positive_1 passes without ever testing 1. Always use each (or each_with_index, each_pair) to generate tests.

Guidelines

For running these suites automatically on every push, see Testing in CI. For more on define_method and class-body code, see Metaprogramming.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents