Running Minitest
Learn how to run Minitest. Learn about Minitest directories, files, test method functionalities, and fixture loading.
We'll cover the following
Rails provides some standard tasks for running all or part of the test suite.
Minitest directories
The one to use most of the time, which is not the Rails default, is rails test
(often bin/rails test
, depending on how our bundle is set up). It grabs any files ending with _test.rb
in the test
directory or any of its subdirectories (except for system tests) and executes them through Minitest. Minitest and Rails use the syntax rails test test/models/task_test.rb
for running a single file or directory. For now, let’s assume we’re using rails test
. In the chapter “Running Tests Faster and Running Faster Tests", we’ll cover better ways to focus on test execution.
Minitest files
When we run rake test
or bundle exec rake test
, the Rake task identifies any files matching the pattern test/**/*_test.rb
and passes them all to Minitest. (The related task rails test:db
first resets the database using db:test:prepare
). Once Minitest gets the list of matching files, it does the following for each file:
-
The Ruby interpreter loads the file. In a Rails context, the line
require test_helper
is important, as thetest_helper
file includes global and Rails-specific setup. -
Inside any subclass of
Minitest::Test
, Minitest identifies test methods in the file, either because the method name starts withtest
or because we’re using the ActiveSupporttest
method directly.
That gives Minitest a list of test methods to run.
Test methods functionality
For each of those methods, it does the following:
- Loads or resets all fixture data, as discussed in Fixtures.
-
Runs all set up blocks. Setup blocks are defined as
def setup
orsetup do
in Rails. -
Runs the test method. The method execution ends when a runtime error or a failed assertion is encountered. Otherwise, it passes. Yay!
-
Runs all teardown blocks. Teardown blocks are declared similarly to set up blocks, but their use is much less common.
-
Rolls back or deletes the fixtures as described in the first bullet point. Each test’s result is passed back to the test runner for display in the console or IDE window running the test.
The following figure shows the flow.
Get hands-on with 1400+ tech skills courses.