The Mocha library is the one Rails uses for its own testing, so it seems natural for a test-double library to use with Minitest. Full Mocha docs are available here.

Installing Mocha

Mocha needs to be installed after Minitest, which requires a slight indirection to ensure our Rails app does the right thing.

First, in the Gemfile’s :test group, we added the Mocha gem:

gem "mocha"

Then, inside the test/test_helper.rb file, we manually require Mocha at any point in the file after the rails/test_help library is loaded:

require "mocha/mini_test"

At that point, we should be good to go. Please see Using Test Doubles as Mocks and Stubs, for a full discussion of test doubles. Here we’ll cover only Mocha syntax.

Mocha full doubles

In Mocha we can call stub to create a full double that is just a set of stubbed methods. The stub is available throughout the test cases.

Get hands-on with 1200+ tech skills courses.