Mocha
Learn mocha, how to install mocha and how to write tests using Mocha.
We'll cover the following...
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.
test "here's a sample stub" dostubby = stub(name: "Paul", weight: 100)assert_equal("Paul", stubby.name)end
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 ...