AWS Developer Tools Blog

Running Your Minitest Unit Test Suite

I have blogged a few times recently about Minitest. With Minitest you need to chose how you will execute your tests. When using other tools, like Rspec, there is a bundled test runner.

$ rspec
............

Finished in 0.03324 seconds
12 examples, 0 failures

Minitest does not provide a test runner as a command line script. One common workaround is to use minitest/autorun.

# inside test/my_class_test.rb
require 'minitest/autorun'

class MyClassTest < Minitest::Test
  ...
end

Now you cn execute your tests using the ruby command:

$ ruby test/my_class_test.rb

Minitest uses very little Ruby magic, but this is one case it indulges. minitest/autorun uses #at_exit to execute tests. This makes it possible for you to specify many test files and have them all run at the end.

Instead of supplying a list of test files at the command line, I prefer to setup a rake task that executes my test files. Here is a simple Rake task file that creates two tasks. The first task executes my unit tests. The second task executes my unit tests while also generating a coverage report.

# inside tasks/test.rake
require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs.push 'test'
  t.pattern = 'test/**/*_test.rb'
  t.warning = true
  t.verbose = true
end

task :default => :test

desc 'Generates a coverage report'
task :coverage do
  ENV['COVERAGE'] = 'true'
  Rake::Task['test'].execute
end

Next, I place the following line at the top of each test file. This allows me to still run the test files from the command line, while loading any shared testing helpers.

require 'test_helper'

Finally my test/test_helper.rb file looks like this:

if ENV['COVERAGE']
  require 'simplecov'
  SimpleCov.start do
    add_filter 'test'
    command_name 'Mintest'
  end
end

require 'minitest/autorun'
require 'my-library'

Running rake from the command line will now run my unit tests. rake coverage will generate a coverage report. This setup is simple and the tests run fast. I hope this helps.

Have fun and keep on Testing!