Home · Blog · Talks · Projects

Using Mocha with Rails 3 and MiniTest

There's been some confusion recently over which versions of Mocha are compatible with which versions of Rails (or more specifically, ActiveSupport). I've added some extra information to the Mocha README, but for extra clarity, I thought I'd post details here. If you're using Test::Unit instead of MiniTest, please read my next post.

If you're loading Mocha using Bundler within a Rails application, you should ensure Mocha is not auto-required and load Mocha manually e.g. at the bottom of test/test_helper.rb.

  # Gemfile in Rails app
  gem "mocha", :require => false

  # At bottom of test_helper.rb
  require "mocha/setup"

Note: Using the latest version of Mocha (0.13.2) with the latest versions of Rails (e.g. 3.2.11, 3.1.10, or 3.0.19), you will see the following Mocha deprecation warning:

    *** Mocha deprecation warning: Change `require 'mocha'` to `require 'mocha/setup'`.

This will happen until new versions of Rails are released incorporating the following pull requests:

These pull requests have all been merged, but unfortunately they have not yet been released and may not be for some time.

The Mocha deprecation warning will not cause any problems, but if you don't like seeing then you could do one of the following:

Option 1 - Disable Mocha deprecation warnings with a Rails initializer

    # config/mocha.rb
    if Rails.env.test? || Rails.env.development?
      require "mocha/version"
      require "mocha/deprecation"
      if Mocha::VERSION == "0.13.2" && Rails::VERSION::STRING == "3.2.11"
        Mocha::Deprecation.mode = :disabled


Option 2 - Use "edge" Rails or one of the relevant "stable" branches of Rails

    # Gemfile
    gem "rails", git: "git://github.com/rails/rails.git", branch: "3-2-stable"
    group :test do
      gem "mocha", :require => false

    # test/test_helper.rb
    require "mocha/setup"

Although obviously it isn't ideal using an unreleased version of Rails. You could always lock things down further by using the Bundler :ref option to restrict the version of Rails to a specific SHA.

Option 3 - Downgrade to Mocha 0.12.8

    # Gemfile in Rails app
    gem "mocha", "~> 0.12.8", :require => false

    # At bottom of test_helper.rb
    require "mocha"

Note: This isn't as bad as it sounds, because there aren't many changes in Mocha 0.13.x that are not in 0.12.x. Please let us know if there are any fixes in 0.13.x that you need in 0.12.x and I will back-port them.

Contact · History · Colophon · Links