How to set up MiniTest?

Andrew picture Andrew · Jul 16, 2011 · Viewed 12.7k times · Source

I'm a fairly novice tester, but have been trying to get better at TDD in Rails.

RSpec works great, but my tests are pretty slow. I've heard that MiniTest is a lot faster, and the MiniTest/Spec DSL looks pretty similar to how I'm used to working with RSpec, so I thought I'd give it a try.

However, I have not been able to find anything on the web that provides a walkthrough of how to setup and run Minitest. I learned how to test from the RSpec book, and I have no idea how Test::Unit or MiniTest are supposed to work. I have the gem in my gemfile, I've written a few simple tests, but I have no idea where to put them or how to run them. I figure this is one of those things that's so obvious nobody has bothered to write it down...

Can anyone explain to me how to setup some some Minitest/spec files and get them running so I can compare the performance against Rspec?

EDIT

Specifically these are the basics I most need to know:

  1. Do you need a test_helper file (like spec_helper) and if so how do you create it?
  2. How do you run minitest? There doesn't seem to be an equivalent to rspec spec or rspec path/to/file_spec.rb, what am I missing?

Thanks!

Answer

Patrick picture Patrick · Dec 6, 2011

This question is similar to How to run all tests with minitest?

Using Ruby 1.9.3 and Rake 0.9.2.2, given a directory layout like this:

Rakefile
lib/alpha.rb
spec/alpha_spec.rb

Here is what alpha_spec.rb might look like:

require 'minitest/spec'
require 'minitest/autorun'  # arranges for minitest to run (in an exit handler, so it runs last)

require 'alpha'

describe 'Alpha' do
  it 'greets you by name' do
    Alpha.new.greet('Alice').must_equal('hello, Alice')
  end
end

And here's Rakefile

require 'rake'
require 'rake/testtask'

Rake::TestTask.new do |t|
  t.pattern = 'spec/**/*_spec.rb'
end

You can run

  • all tests: rake test
  • one test: ruby -Ilib spec/alpha_spec.rb

I don't know if using a spec_helper.rb with minitest is common or not. There does not appear to be a convenience method for loading one. Add this to the Rakefile:

require 'rake'
require 'rake/testtask'

Rake::TestTask.new do |t|
  t.pattern = 'spec/**/*_spec.rb'
  t.libs.push 'spec'
end

Then spec/spec_helper.rb can contain various redundant things:

require 'minitest/spec'
require 'minitest/autorun'
require 'alpha'

And spec/alpha_spec.rb replaces the redundant parts with:

require 'spec_helper'
  • all tests: rake test
  • one test: ruby -Ilib -Ispec spec/alpha_spec.rb