This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Minitest Cheatsheet

A quick reference guide for Ruby Minitest: unit testing, BDD specs, expectation matchers, assertions, Minitest::Mock, and reporters.

· Published

Minitest provides a complete suite of testing facilities supporting TDD, BDD, mocking, and benchmarking for Ruby.

Unit Testing (Minitest::Test)

require 'minitest/autorun'

class TestUser < Minitest::Test
  def setup
    @user = User.new(name: "Alice", email: "[email protected]")
  end

  def teardown
    @user = nil
  end

  def test_name_attribute
    assert_equal "Alice", @user.name
  end

  def test_active_status
    refute @user.banned?
  end
end

BDD Specs (describe / it)

require 'minitest/autorun'

describe User do
  before do
    @user = User.new("Bob")
  end

  let(:account) { Account.new(balance: 100) }

  it "must return valid formatted name" do
    _(@user.name).must_equal "Bob"
  end

  it "must maintain sufficient balance" do
    _(account.balance).must_be :>=, 50
  end
end

Assertions & Expectations

Assertion (assert) Refutation (refute) Spec Expectation (_())
assert test refute test _(test).must_equal true
assert_equal a, b refute_equal a, b _(b).must_equal a
assert_nil x refute_nil x _(x).must_be_nil
assert_empty list refute_empty list _(list).must_be_empty
assert_includes list, item refute_includes list, item _(list).must_include item
assert_match /re/, str refute_match /re/, str _(str).must_match /re/
assert_instance_of Cls, obj refute_instance_of _(obj).must_be_instance_of Cls
assert_kind_of Mod, obj refute_kind_of _(obj).must_be_kind_of Mod
assert_raises(Err) { ... } — _{ ... }.must_raise Err
assert_silent { ... } — _{ ... }.must_be_silent

Mocking with Minitest::Mock

require 'minitest/autorun'

describe PaymentGateway do
  it "charges the credit card through processor" do
    processor = Minitest::Mock.new
    # expect(method, return_value, expected_arguments)
    processor.expect :charge, true, [100.0, "tok_visa"]

    gateway = PaymentGateway.new(processor)
    gateway.process_payment(100.0, "tok_visa")

    assert processor.verify
  end
end

Custom Reporters

gem 'minitest-reporters'

require 'minitest/reporters'
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new

References

Related topics