Mocha
Explore how to use the Mocha library alongside Minitest to create test doubles, including stubs and mocks. Understand Mocha syntax for verifying method calls, setting expectations, and handling arguments to write precise and reliable tests for Ruby on Rails applications.
We'll cover the following...
- Installing Mocha
- Mocha full doubles
- Mocha test doubles verification
- Mocha errors
- Mocha partial doubles verification
- Mocha stubbed method specification
- Expectations mocking with Mocha
- Stub instance methods
- Mocha mock objects
- Expectations mocking with Mocha
- Mocha specification arguments
- Parameters matchers in Mocha
- Mocha negating matchers
- Mocha resources
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.
Mocha test doubles verification
Mocha has verification syntax for full doubles. In Mocha, we use responds_like and responds_like_instance_of to verify that the ...