Assertions

suggest change

An assertion is a statement that something must be true at a given point in the program. If it's false, the program has a bug, and the assertion makes it fail right there with a clear message. Without the assertion, the bad value would travel further and break something far away from the real cause.

Ruby has no assert keyword and no built-in assert method in the core language. Assertions show up in two places:

This article covers both. All examples were run with Ruby 4.0, Minitest 6.0, test-unit 3.7 and RSpec 3.13.

Assertions in application code

The idiomatic way to assert in Ruby is a guard clause that raises:

def withdraw(amount)
  raise ArgumentError, "amount must be positive, got #{amount}" unless amount.positive?
  raise ArgumentError, "insufficient funds" if amount > @balance

  @balance -= amount
end

If you prefer the look of an assert call, it's a three-line method:

class AssertionError < StandardError; end

def assert(condition, message = "assertion failed")
  raise AssertionError, message unless condition
end

def average(numbers)
  assert numbers.is_a?(Array), "expected an Array, got #{numbers.class}"
  assert !numbers.empty?, "can't average an empty list"
  numbers.sum.fdiv(numbers.size)
end

p average([1, 2, 3, 4])

begin
  average([])
rescue AssertionError => e
  puts "#{e.class}: #{e.message}"
end

average("1,2,3")
2.5
AssertionError: can't average an empty list
a1.rb:4:in 'Object#assert': expected an Array, got String (AssertionError)
	from a1.rb:8:in 'Object#average'
	from a1.rb:21:in '<main>'

The backtrace points at the caller (average, line 8), which is where the broken assumption lives.

Defining assert on Object like this is fine for a script. In a library, put it in a module (see below) so you don't add a public-looking assert method to every object in someone else's program.

Which exception to raise

One subtle choice is the superclass of the custom class. A bare rescue (or rescue => e) catches only StandardError and its subclasses. If an assertion failure means "the program is in a state I didn't think possible", you may not want some generic rescue deep in the call stack to swallow it:

class SoftAssertionError < StandardError; end
class HardAssertionError < Exception; end

def risky(error_class)
  begin
    raise error_class, "invariant broken"
  rescue => e
    puts "swallowed #{e.class}"
  end
  puts "kept going after #{error_class}"
end

risky(SoftAssertionError)
risky(HardAssertionError)
swallowed SoftAssertionError
kept going after SoftAssertionError
a5.rb:6:in 'Object#risky': invariant broken (HardAssertionError)
	from a5.rb:14:in '<main>'

Inheriting from Exception is what Minitest does for its own Minitest::Assertion, so a failed assertion inside a test isn't accidentally rescued by the code under test. For application code, StandardError is the usual and safer default: web servers and job runners rescue StandardError to log the error and keep serving other requests, and an Exception subclass would bypass that and crash the worker.

Assertions built into core methods

Many core methods are assertions in disguise. Using them instead of the lenient alternatives catches bad data at the point where it enters:

config = { "port" => "8080" }

p config.fetch("port")
begin
  config.fetch("host")
rescue KeyError => e
  puts "#{e.class}: #{e.message}"
end
p config.fetch("host", "localhost")

p Integer("42")
begin
  Integer("42abc")
rescue ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
p Integer("42abc", exception: false)

p [10, 20].fetch(1)
begin
  [10, 20].fetch(5)
rescue IndexError => e
  puts "#{e.class}: #{e.message}"
end
"8080"
KeyError: key not found: "host"
"localhost"
42
ArgumentError: invalid value for Integer(): "42abc"
nil
20
IndexError: index 5 outside of array bounds: -2...2

Compare with the lenient versions: config["host"] silently returns nil, and "42abc".to_i silently returns 42. When a value is required, fetch and Integer() assert that it's there and valid.

Pattern matching as an assertion

The rightward pattern match expr => pattern raises NoMatchingPatternError if the value doesn't match. It checks the structure and types of nested data and binds variables in a single expression, which makes it a compact assertion for parsed JSON, config files or API responses:

response = { status: 200, body: { user: { id: 7, name: "Ann" } } }

# => raises if the shape doesn't match, and binds variables
response => { status: 200, body: { user: { id: Integer => id, name: String => name } } }
puts "user #{id}: #{name}"

bad = { status: 200, body: { user: { id: "7", name: "Ann" } } }
begin
  bad => { body: { user: { id: Integer } } }
rescue NoMatchingPatternError => e
  puts "#{e.class}: #{e.message}"
end

begin
  bad => { body: { account: } }
rescue NoMatchingPatternKeyError => e
  puts "#{e.class}: #{e.message}"
  p e.key
end

# `in` returns true/false instead of raising
p((bad in { body: { user: { id: Integer } } }))
p((response in { status: 200..299 }))
user 7: Ann
NoMatchingPatternError: {status: 200, body: {user: {id: "7", name: "Ann"}}}: Integer === "7" does not return true
NoMatchingPatternKeyError: {status: 200, body: {user: {id: "7", name: "Ann"}}}: key not found: :account
:account
false
true

NoMatchingPatternKeyError is a subclass of NoMatchingPatternError, raised when a required hash key is missing. Its key method returns the missing key.

Note the double parentheses around bad in .... p(x in pat) is a syntax error, and ok = x in pat parses as (ok = x) in pat, so wrap the in expression in its own parentheses.

Expensive checks and turning assertions off

Some invariants are costly to check: "this array is sorted", "this tree is balanced". Languages like Java and C let you compile assertions out of production builds. Ruby has no such switch, but you can build one. Passing the condition as a block means it isn't even evaluated when checks are disabled:

module Assert
  class Error < StandardError; end

  ENABLED = ENV.fetch("RUBY_ASSERTIONS", "1") != "0"

  def self.check(message = "assertion failed")
    return unless ENABLED
    raise Error, message unless yield
  end
end

def merge_sorted(a, b)
  Assert.check("inputs must be sorted") { a.each_cons(2).all? { _1 <= _2 } && b.each_cons(2).all? { _1 <= _2 } }

  result = []
  i = j = 0
  while i < a.size && j < b.size
    if a[i] <= b[j]
      result << a[i]; i += 1
    else
      result << b[j]; j += 1
    end
  end
  result.concat(a[i..]).concat(b[j..])

  Assert.check("result must have all elements") { result.size == a.size + b.size }
  result
end

p merge_sorted([1, 4, 9], [2, 3, 10])
p merge_sorted([5, 1], [2])

With assertions enabled (the default):

[1, 2, 3, 4, 9, 10]
a4.rb:8:in 'Assert.check': inputs must be sorted (Assert::Error)
	from a4.rb:13:in 'Object#merge_sorted'
	from a4.rb:31:in '<main>'

With RUBY_ASSERTIONS=0 ruby a4.rb the check is skipped and the function quietly returns garbage:

[1, 2, 3, 4, 9, 10]
[2, 5, 1]

That second output is the argument against disabling assertions. The check costs CPU time, but without it you get wrong results instead of an error. Disable only the checks that are measurably expensive (see Benchmarks), and never put checks that validate external input behind such a switch.

Also keep side effects out of assertion blocks. If Assert.check { queue.pop } is disabled, the pop doesn't happen either, and the program behaves differently with and without checks.

Assertions in Minitest

Minitest ships with Ruby as a bundled gem. Each assertion is a method on Minitest::Test. These tests exercise a small shopping cart:

# cart.rb
class Cart
  Item = Data.define(:name, :price, :qty)

  attr_reader :items

  def initialize
    @items = []
  end

  def add(name, price, qty: 1)
    raise ArgumentError, "qty must be positive, got #{qty}" unless qty.positive?
    @items << Item.new(name, price, qty)
    self
  end

  def total
    items.sum { |i| i.price * i.qty }
  end

  def empty? = items.empty?

  def print_receipt
    items.each { |i| puts "#{i.name} x#{i.qty}" }
    puts "total: #{total}"
  end
end
# cart_test.rb
require "minitest/autorun"
require_relative "cart"

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

  def test_new_cart_is_empty
    assert @cart.empty?
    assert_predicate @cart, :empty?
    assert_empty @cart.items
    assert_equal 0, @cart.total
  end

  def test_total
    @cart.add("pen", 1.10, qty: 3).add("book", 12.5)
    assert_in_delta 15.8, @cart.total, 0.001
    assert_equal 2, @cart.items.size
    assert_includes @cart.items.map(&:name), "book"
    refute_empty @cart.items
  end

  def test_rejects_bad_quantity
    error = assert_raises(ArgumentError) { @cart.add("pen", 1, qty: 0) }
    assert_match(/must be positive/, error.message)
  end

  def test_receipt_output
    @cart.add("pen", 2, qty: 2)
    assert_output("pen x2\ntotal: 4\n") { @cart.print_receipt }
  end

  def test_item_shape
    @cart.add("pen", 2)
    assert_pattern { @cart.items.first => { name: String, price: Numeric, qty: 1 } }
    assert_kind_of Data, @cart.items.first
    assert_instance_of Cart::Item, @cart.items.first
  end
end
$ ruby cart_test.rb
Run options: --seed 62323

# Running:

.....

Finished in 0.002407s, 2076.8432 runs/s, 7892.0042 assertions/s.

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

The most useful assertions:

Assertion Passes when
assert(value) value is truthy
assert_equal(expected, actual) expected == actual
assert_nil(value) value.nil?
assert_in_delta(expected, actual, delta) (expected - actual).abs <= delta
assert_includes(collection, obj) collection.include?(obj)
assert_empty(obj) obj.empty?
assert_predicate(obj, :pred?) obj.pred? is truthy
assert_match(regexp, string) regexp =~ string
assert_kind_of(klass, obj) obj.kind_of?(klass)
assert_instance_of(klass, obj) obj.instance_of?(klass)
assert_raises(Error) { ... } the block raises Error; returns the exception
assert_output(stdout, stderr) { ... } the block prints the given text
assert_pattern { expr => pattern } the pattern match doesn't raise

Almost every assert_* has a refute_* counterpart that asserts the opposite: refute_nil, refute_includes, refute_empty, and so on.

Reading failures

How you write an assertion decides how useful its failure message is. Here are four failing tests:

require "minitest/autorun"
require_relative "cart"

class FailingTest < Minitest::Test
  def test_float_total
    cart = Cart.new.add("pen", 1.10, qty: 3)
    assert_equal 3.3, cart.total
  end

  def test_bare_assert
    cart = Cart.new.add("pen", 2)
    assert cart.total > 5
  end

  def test_assert_with_message
    cart = Cart.new.add("pen", 2)
    assert cart.total > 5, "expected total > 5, got #{cart.total}"
  end

  def test_hash_diff
    expected = { name: "pen", price: 2, qty: 1, tags: ["office"] }
    actual   = { name: "pen", price: 2, qty: 2, tags: ["office"] }
    assert_equal expected, actual
  end
end
  1) Failure:
FailingTest#test_hash_diff [fail_test.rb:23]:
--- expected
+++ actual
@@ -1 +1 @@
-{name: "pen", price: 2, qty: 1, tags: ["office"]}
+{name: "pen", price: 2, qty: 2, tags: ["office"]}


  2) Failure:
FailingTest#test_float_total [fail_test.rb:7]:
Expected: 3.3
  Actual: 3.3000000000000003

  3) Failure:
FailingTest#test_assert_with_message [fail_test.rb:17]:
expected total > 5, got 2

  4) Failure:
FailingTest#test_bare_assert [fail_test.rb:12]:
Expected false to be truthy.

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

What to take from this:

Minitest 6 also refuses assert_equal nil, value and fails with Use assert_nil if expecting nil. This catches tests where the expected value accidentally became nil, such as a misspelled variable in a helper.

Custom assertions

When the same check appears in many tests, turn it into an assertion method. Call assert / refute inside so the assertion counter and failure reporting keep working, and build the message lazily with message:

require "minitest/autorun"

module SortedAssertions
  def assert_sorted(list, msg = nil)
    msg = message(msg) { "Expected #{mu_pp(list)} to be sorted" }
    assert list.each_cons(2).all? { |a, b| a <= b }, msg
  end

  def refute_sorted(list, msg = nil)
    msg = message(msg) { "Expected #{mu_pp(list)} not to be sorted" }
    refute list.each_cons(2).all? { |a, b| a <= b }, msg
  end
end

class SortTest < Minitest::Test
  include SortedAssertions

  def test_sorted
    assert_sorted [1, 2, 2, 5]
    refute_sorted [3, 1]
  end

  def test_not_sorted
    assert_sorted [1, 5, 2], "scores came back out of order"
  end
end
  1) Failure:
SortTest#test_not_sorted [custom_test.rb:24]:
scores came back out of order.
Expected [1, 5, 2] to be sorted.

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

mu_pp is Minitest's pretty-printer for values in messages. message(msg) { ... } puts the caller's custom message in front of the default one. The block is only evaluated when the assertion fails, so building an expensive message costs nothing for passing tests. Note the failure is reported at the line in the test, not inside assert_sorted: Minitest filters its own and your assertion's frames out of the location.

To run the same assertion over a table of inputs, see Parameterized tests.

test-unit and power_assert

test-unit, also a bundled gem, has assertions like Minitest's (assert_equal, assert_raise, assert_in_delta). Its standout feature is assert with a block, powered by the power_assert gem. You write a plain Ruby expression and, on failure, it shows the value of every sub-expression:

require "test/unit"

class PowerTest < Test::Unit::TestCase
  def test_average
    prices = [2, 3, 5]
    assert { prices.sum / prices.size == prices.max - 1 }
  end
end
Failure: test_average(PowerTest):
      assert { prices.sum / prices.size == prices.max - 1 }
               |      |   | |      |    |  |      |   |
               |      |   | |      |    |  |      |   4
               |      |   | |      |    |  |      5
               |      |   | |      |    |  [2, 3, 5]
               |      |   | |      |    false
               |      |   | |      3
               |      |   | [2, 3, 5]
               |      |   3
               |      10
               [2, 3, 5]

You can see at a glance that 10 / 3 is 3 (integer division) while the right side is 4. You get this detail without having to pick the right specialized assertion.

Expectations in RSpec

RSpec calls its assertions expectations: expect(actual).to matcher and expect(actual).not_to matcher. Matchers read like English and produce descriptive failures:

# cart_spec.rb
require_relative "cart"

RSpec::Matchers.define :be_sorted do
  match { |list| list.each_cons(2).all? { |a, b| a <= b } }
  failure_message { |list| "expected #{list.inspect} to be sorted" }
end

RSpec.describe Cart do
  subject(:cart) { Cart.new }

  it "starts empty" do
    expect(cart).to be_empty
    expect(cart.total).to eq(0)
  end

  it "adds up prices" do
    cart.add("pen", 1.10, qty: 3).add("book", 12.5)
    expect(cart.total).to be_within(0.001).of(15.8)
    expect(cart.items.map(&:name)).to contain_exactly("book", "pen")
    expect(cart.items.first).to have_attributes(name: "pen", qty: 3)
  end

  it "rejects a zero quantity" do
    expect { cart.add("pen", 1, qty: 0) }.to raise_error(ArgumentError, /must be positive/)
  end

  it "changes the total" do
    expect { cart.add("pen", 2) }.to change(cart, :total).from(0).to(2)
  end

  it "reports every failed expectation", :aggregate_failures do
    cart.add("pen", 2)
    expect(cart.total).to eq(3)
    expect(cart.items.size).to eq(2)
  end

  it "uses a custom matcher" do
    expect([3, 1, 2]).to be_sorted
  end
end
$ rspec cart_spec.rb
F..F..

Failures:

  1) Cart uses a custom matcher
     Failure/Error: expect([3, 1, 2]).to be_sorted
       expected [3, 1, 2] to be sorted
     # ./cart_spec.rb:38:in 'block (2 levels) in <top (required)>'

  2) Cart reports every failed expectation
     Got 2 failures:

     2.1) Failure/Error: expect(cart.total).to eq(3)

            expected: 3
                 got: 2

            (compared using ==)
          # ./cart_spec.rb:33:in 'block (2 levels) in <top (required)>'

     2.2) Failure/Error: expect(cart.items.size).to eq(2)

            expected: 2
                 got: 1

            (compared using ==)
          # ./cart_spec.rb:34:in 'block (2 levels) in <top (required)>'

6 examples, 2 failures

Some things to note:

Guidelines

For investigating a failed assertion interactively, see Debugging, and for the basics of raising and rescuing, see Exceptions.

Feedback about page:

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



Table Of Contents