Skip to content
Mocha is a mocking and stubbing library for Ruby
Branch: master
Clone or download
floehopper Merge pull request #354 from deepj/truffleruby
Run tests in TruffleRuby in Travis CI
Latest commit d986fd2 Mar 20, 2019
Type Name Latest commit message Commit time
Failed to load latest commit information.
bin Update to latest bundler in build-matrix builds Oct 7, 2018
docs Update documentation for v1.8.0 release Jan 15, 2019
gemfiles Make tests for Ruby version more consistent Aug 15, 2016
lib Bump version and update release notes Jan 15, 2019
test Avoid calling Kernel#format from ObjectMethods#mocha_inspect Oct 7, 2018
yard-templates/default/layout/html Switch fm Google Analytics -> Tag Manager & use new property ID Jan 15, 2019
.gemtest Make testable by rubygems-test. Feb 3, 2011
.gitignore Add documentation to repo Jan 15, 2019
.rubocop.yml Fix Style/NumericPredicate violations manually Jul 26, 2018
.rubocop_todo.yml Set rubocop TargetRubyVersion to earlist possible (v2.2) Jul 26, 2018
.travis.yml Allow to fail tests in TruffleRuby Mar 18, 2019
.yardopts Add Google Analytics javascript to Mocha docs. Jan 8, 2013 Tweaks to wording in CONTRIBUTING Oct 7, 2018 Ensure all files have a newline at end-of-file. Feb 18, 2013
Gemfile Avoid deprecation warning in Bundler v1.2.4. Feb 18, 2013 Ensure all files have a newline at end-of-file. Feb 18, 2013 Correction to release process in README Jan 15, 2019 Bump version and update release notes Jan 15, 2019
Rakefile Update README to reflect new release process Jan 15, 2019
init.rb Ensure all files have a newline at end-of-file. Feb 18, 2013
mocha.gemspec Change documentation domain -> Jan 15, 2019

Mocha Build Status Gem Version SemVer


  • A Ruby library for mocking and stubbing.
  • A unified, simple and readable syntax for both full & partial mocking.
  • Built-in support for MiniTest and Test::Unit.
  • Supported by many other test frameworks.



Install the latest version of the gem with the following command...

$ gem install mocha

Note: If you are intending to use Mocha with Test::Unit or MiniTest, you should only setup Mocha after loading the relevant test library...

require 'rubygems'
gem 'mocha'
require 'test/unit'
require 'mocha/test_unit'
require 'rubygems'
gem 'mocha'
require 'minitest/unit'
require 'mocha/minitest'


If you're using Bundler, include Mocha in the Gemfile and then setup Mocha later once you know the test library has been loaded...

# Gemfile
gem "mocha"

# Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'`
require "test/unit"
require "mocha/test_unit"
# Gemfile
gem "mocha"

# Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'`
require "minitest/unit"
require "mocha/minitest"


If you're loading Mocha using Bundler within a Rails application, you should setup Mocha manually e.g. at the bottom of your test_helper.rb.

# Gemfile in Rails app
gem 'mocha'

# At bottom of test_helper.rb (or at least after `require 'rails/test_help'`)
require 'mocha/minitest'

RSpec includes a mocha adapter. Just tell RSpec you want to mock with :mocha:

# Gemfile in Rails app
gem 'mocha'

# Within `spec/spec_helper.rb`
RSpec.configure do |config|
  config.mock_with :mocha

Note: There is no need to use a require statement to setup Mocha; RSpec does this itself.

Rails Plugin

Install the Rails plugin...

$ rails plugin install git://

Note: As of version 0.9.8, the Mocha plugin is not automatically setup at plugin load time. Instead it must be manually setup e.g. at the bottom of your test_helper.rb.

# At bottom of test_helper.rb (or at least after `require 'rails/test_help'`)
require 'mocha/minitest'

Known Issues

  • In Mocha v1.2.0 there is a scenario where stubbing a class method originally defined in a module hangs the Ruby interpreter due to a bug in Ruby v2.3.1. See #272. This was fixed in Mocha v1.2.1.
  • Since v1.1.0 Mocha has used prepended modules internally for stubbing methods. There is an obscure Ruby bug in many (but not all) versions of Ruby between v2.0 & v2.3 which under certain circumstances may cause your Ruby interpreter to hang. See the Ruby bug report for more details. The bug has been fixed in Ruby v2.3.3 & v2.4.0.
  • Stubbing an aliased class method, where the original method is defined in a module that's used to extend the class doesn't work in Ruby 1.8.x. See stub_method_defined_on_module_and_aliased_test.rb for an example of this behaviour.
  • 0.13.x versions cause a harmless, but annoying, deprecation warning when used with Rails 3.2.0-3.2.12, 3.1.0-3.1.10 & 3.0.0-3.0.19.
  • 0.11.x versions don't work with Rails 3.2.13 (TypeError: superclass mismatch for class ExpectationError). See #115.
  • Versions 0.10.2, 0.10.3 & 0.11.0 of the Mocha gem were broken. Please do not use these versions.
  • Versions 0.9.6 & 0.9.7 of the Mocha Rails plugin were broken. Please do not use these versions.


Quick Start

require 'test/unit'
require 'mocha/test_unit'

class MiscExampleTest < Test::Unit::TestCase
  def test_mocking_a_class_method
    product =
    assert_equal product, Product.find(1)

  def test_mocking_an_instance_method_on_a_real_object
    product =

  def test_stubbing_instance_methods_on_real_objects
    prices = [stub(:pence => 1000), stub(:pence => 2000)]
    product =
    assert_equal [1000, 2000], product.prices.collect {|p| p.pence}

  def test_stubbing_an_instance_method_on_all_instances_of_a_class
    product =
    assert_equal 'stubbed_name',

  def test_traditional_mocking
    object = mock('object')
    object.expects(:expected_method).with(:p1, :p2).returns(:result)
    assert_equal :result, object.expected_method(:p1, :p2)

  def test_shortcuts
    object = stub(:method1 => :result1, :method2 => :result2)
    assert_equal :result1, object.method1
    assert_equal :result2, object.method2

Mock Objects

class Enterprise
  def initialize(dilithium)
    @dilithium = dilithium

  def go(warp_factor)
    warp_factor.times { @dilithium.nuke(:anti_matter) }

require 'test/unit'
require 'mocha/test_unit'

class EnterpriseTest < Test::Unit::TestCase
  def test_should_boldly_go
    dilithium = mock()
    dilithium.expects(:nuke).with(:anti_matter).at_least_once  # auto-verified at end of test
    enterprise =

Partial Mocking

class Order
  attr_accessor :shipped_on

  def total_cost
    line_items.inject(0) { |total, line_item| total + line_item.price } + shipping_cost

  def total_weight
    line_items.inject(0) { |total, line_item| total + line_item.weight }

  def shipping_cost
    total_weight * 5 + 10

  class << self
    def find_all
      # Database.connection.execute('select * from orders...

    def number_shipped_since(date) { |order| order.shipped_on > date }.length

    def unshipped_value
      find_all.inject(0) { |total, order| order.shipped_on ? total : total + order.total_cost }

require 'test/unit'
require 'mocha/test_unit'

class OrderTest < Test::Unit::TestCase
  # illustrates stubbing instance method
  def test_should_calculate_shipping_cost_based_on_total_weight
    order =
    assert_equal 60, order.shipping_cost

  # illustrates stubbing class method
  def test_should_count_number_of_orders_shipped_after_specified_date
    now =; week_in_secs = 7 * 24 * 60 * 60
    order_1 =; order_1.shipped_on = now - 1 * week_in_secs
    order_2 =; order_2.shipped_on = now - 3 * week_in_secs
    Order.stubs(:find_all).returns([order_1, order_2])
    assert_equal 1, Order.number_shipped_since(now - 2 * week_in_secs)

  # illustrates stubbing instance method for all instances of a class
  def test_should_calculate_value_of_unshipped_orders
    assert_equal 30, Order.unshipped_value

Thread safety

Mocha is currently not thread-safe. There are two main reasons for this: (a) in multi-threaded code Mocha exceptions may be raised in a thread other than the one which is running the test and thus a Mocha exception may not be correctly intercepted by Mocha exception handling code; and (b) partial mocking changes the state of objects in the ObjectSpace which is shared across all threads in the Ruby process and this access to what is effectively global state is not synchronized.

Expectation matching / invocation order

Stubs and expectations are basically the same thing. A stub is just an expectation of zero or more invocations. The Expectation#stubs method is syntactic sugar to make the intent of the test more explicit.

When a method is invoked on a mock object, the mock object searches through its expectations from newest to oldest to find one that matches the invocation. After the invocation, the matching expectation might stop matching further invocations.

See the documentation for Mocha::Mock for further details.


If you want, Mocha can generate a warning or raise an exception when:

  • stubbing a method unnecessarily
  • stubbing method on a non-mock object
  • stubbing a non-existent method
  • stubbing a non-public method

See the documentation for Mocha::Configuration for further details.

Useful Links


See this list of contributors.

Releasing a new version

$ MOCHA_GENERATE_DOCS=true bundle install

$ curl -u > ~/.gem/credentials; chmod 0600 ~/.gem/credentials`
  • Release gem to Rubygems:
$ rake release
[runs tests]
mocha 1.2.0 built to pkg/mocha-1.2.0.gem.
Tagged v1.2.0.
Pushed git commits and tags.
Pushed mocha 1.2.0 to


Mocha was initially harvested from projects at Reevoo. It's syntax is heavily based on that of jMock.


© Copyright Revieworld Ltd. 2006

You may use, copy and redistribute this library under the same terms as Ruby itself or under the MIT license.

You can’t perform that action at this time.