Mocha
Learn mocha, how to install mocha and how to write tests using Mocha.
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.
Get hands-on with 1400+ tech skills courses.