Ruby, JavaScript, Sass, iOS. Stinky Cheese & Beer Advocate. Working at CustomInk and loving it!

Using MiniTest::Spec With Rails

So after a few blog post on the subject of MiniTest::Spec, I finally have a simple solution for Rails 3 that leverages MiniTest's spec DSL. I introduce to you the minitest-spec-rails gem. MiniTestSpecRails defines a Test::Unit::TestCase class that subclasses MiniTest::Spec. It implements only what is needed to make Rails happy.

Once you bundle the gem in your Rails application, it will satisfy the require "test/unit/testcase" from ActiveSupport's test case. Tricking it to use MiniTest::Spec instead of MiniTest::Unit. Here is an example Gemfile that shows the usage of MiniTestSpecRails. That is all you have to do!

group :test do
  gem 'minitest-spec-rails'


Since MinitTest::Spec is built on top of MiniTest::Unit which is technically a replacement for Test::Unit, there is not a lot that can go wrong. With minitest-spec-rails, we finally have a working solution by replacing MiniTest::Spec as the superclass for ActiveSupport::TestCase. This solution is drop dead simple and does not require you to recreate a new test case in your test_helper.rb or to use generators supplied by gems like minitest-rails.

This means two things. First, older Rails applications can switch to MiniTest::Spec now by simply installing this gem. Second, as Rails itself evolves to eventually leverage MiniTest::Spec, your test case code will not have to change. About the only gotcha is a few missing assertions available in Test::Unit that are changed or no longer available in MiniTest. For example, assert_raise vs assert_raises and there is no such thing as assert_nothing_raised. Code you would have had to change eventually anyway.

New Assertion Styles

One thing that I try to do is to change my test assertions from the old Test::Unit style to the new MiniTest::Spec style. I commonly use this cheat sheet to remember them. For instance:

# This:

# Would Become This:

Likewise, MiniTest::Spec is consistently getting new features added. One patch that I advocated for now allows the must_be and wont_be low-level assertions to work with a predicate method symbol. Meaning, if the symbol ends in a question mark, then it will implicitly call that mehod on the subject for truthy or falsy matching. For instance:

@user.must_be :valid?

Known Issues

None that I know of yet. Try it out and report any issues to our github project page. If you have been using minitest-spec-rails, I would love to hear about it too!