Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 37 ยท Testing, Jobs and Deployment

Testing Rails with Minitest

Learn how Rails tests work: Minitest basics, assertions, setup and teardown, model tests, fixtures, running tests with bin/rails test, and the testing pyramid. Includes runnable Minitest examples.

Tests are small programs that check your code still does what you think it does. A Rails app without tests becomes scary to change: every edit might break something far away. With tests, you change code, run one command, and know within seconds whether you broke anything.

Rails uses Minitest by default. It is a real Ruby library that ships with Ruby itself, so the Minitest examples in this lesson really run on this site. The Rails parts (fixtures, the database, bin/rails test) are shown as read-only code, because the runner has no Rails and no database. Where it matters, we use a plain Ruby stand-in for the model and say so.

Your first test

Every Rails app has a test/ folder that mirrors app/:

TEXT
test/
  models/         # tests for app/models
  controllers/    # tests for controllers
  integration/    # multi-step flows through several controllers
  system/         # real-browser tests (Capybara)
  jobs/  mailers/ helpers/
  fixtures/       # sample data in YAML
  test_helper.rb

A model test looks like this (read-only; it needs a database):

Ruby
# test/models/post_test.rb
require "test_helper"

class PostTest < ActiveSupport::TestCase
  test "is invalid without a title" do
    post = Post.new(title: nil)
    assert_not post.valid?
    assert_includes post.errors[:title], "can't be blank"
  end

  test "slug is built from the title" do
    assert_equal "hello-world", Post.new(title: "Hello World").slug
  end
end

test "..." do ... end is a Rails convenience that turns the sentence into a method named test_is_invalid_without_a_title. Under it is plain Minitest. Run tests with:

SH
bin/rails test                       # everything except system tests
bin/rails test test/models           # one folder
bin/rails test test/models/post_test.rb:7   # the test at line 7
bin/rails test -n "/slug/"           # tests whose name matches

Minitest you can run

Here is a real Minitest::Test class. The code runs each test and prints a one-line result. (A normal project would just call bin/rails test, which prints a summary; this loop keeps our output stable.)

Ruby Real Minitest: pass, fail and error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Two outcomes that look alike are different: a failure means an assertion was false (your expectation was wrong), an error means the code crashed (a bug or a typo). Read the message first, then the line number.

The assertions you will use most

Assertion Passes when
assert x / assert_not x (Rails alias for refute) x is truthy / falsy
assert_equal expected, actual they are == (note the order: expected first)
assert_nil x x is nil
assert_includes collection, item collection includes item
assert_match /regex/, string string matches
assert_raises(Error) { ... } block raises that error
assert_in_delta 0.3, 0.1 + 0.2, 0.0001 floats are close
assert_difference "Post.count", 1 do ... end the count changed by 1 (Rails)
assert_no_difference "User.count" do ... end the count did not change (Rails)
assert_enqueued_jobs 1 do ... end a job was queued (Rails)

Always put the expected value first, or failure messages read backwards.

What makes a good test

A good test is...

Focused One behavior, one reason to fail
Fast No sleeping, no network
Repeatable Same result every run
Readable The name states the rule

If a test needs a comment to explain it, rename it.

1 / 2

Test behavior and rules, not implementation: assert what the method returns or changes, not which private methods it called. Cover the edge cases (empty, nil, zero, duplicates, the boundary value) as well as the happy path.

Fixtures and the test database

Rails loads sample rows from test/fixtures/*.yml into a separate test database before the run, and wraps every test in a transaction that is rolled back, so tests cannot affect each other:

YAML
# test/fixtures/users.yml
ana:
  email: [email protected]
  password_digest: <%= BCrypt::Password.create("secret", cost: 4) %>

# test/fixtures/posts.yml
first:
  title: First post
  user: ana          # refers to the fixture above by name
Ruby
test "author name" do
  assert_equal "[email protected]", posts(:first).user.email
end

posts(:first) returns the record. Fixtures are fast because they load once, but a large web of them gets hard to follow, so keep them few and meaningful; build special cases inside the test (Post.create!(...)) or with a factory library such as FactoryBot.

Stand-in: how a test framework works

The last example is a 20-line imitation of Minitest so the magic is not magic: collect test_ methods, run setup, rescue failures, count.

Ruby Stand-in: a tiny test runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Real Minitest adds assertions, random ordering (so hidden dependencies between tests show up), parallel runs and reporters, but the loop is the same.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between a test failure and a test error in Minitest?

    A failure means an assert did not hold. An error means the code raised something unexpected, such as NoMethodError.
  2. 2. Which argument order is correct?

    Minitest prints 'Expected: a, Actual: b', so put the expected value first or the message misleads you.
  3. 3. What does setup do in a Minitest class?

    setup runs before every test so each starts from a fresh state. teardown runs after each one.
  4. 4. How do Rails tests avoid affecting each other through the database?

    Transactional tests roll back after each test, so rows created in one test vanish before the next.

Summary

  • Rails ships Minitest; test "name" do defines tests, bin/rails test runs them.
  • Failures are false assertions, errors are crashes; read the message and the line.
  • Use setup for fresh state, assert expected-then-actual, and test behavior plus edge cases.
  • Fixtures load YAML rows into a test database; transactions keep tests isolated.

Next: Integration and system tests