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' end
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_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: assert_not_nil @foo.bar # Would Become This: @foo.bar.wont_be_nil
Likewise, MiniTest::Spec is consistently getting new features added. One patch that I advocated for now allows the
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:
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!
- MiniTest::Spec For Rails - Drop in MiniTest::Spec support for Rails 3.
- MiniBacktrace - Make the Rails backtrace cleaner work.
- MiniTest Rails - Official minitest project for Rails that uses generators.