• Stars
    star
    1,209
  • Rank 38,754 (Top 0.8 %)
  • Language
    Ruby
  • License
    Other
  • Created about 16 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A mocking and stubbing library for Ruby

Mocha CircleCI status of freerange/mocha Gem Version

Description

  • A Ruby library for mocking and stubbing - but deliberately not (yet) faking or spying.
  • 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.

Intended Usage

Mocha is intended to be used in unit tests for the Mock Object or Test Stub types of Test Double, not the Fake Object or Test Spy types. Although it would be possible to extend Mocha to allow the implementation of fakes and spies, we have chosen to keep it focused on mocks and stubs.

Installation

Gem

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...

Test::Unit
require 'rubygems'
gem 'mocha'
require 'test/unit'
require 'mocha/test_unit'
Minitest
require 'rubygems'
gem 'mocha'
require 'minitest/autorun'
require 'mocha/minitest'

Bundler

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

Test::Unit
# Gemfile
gem 'mocha'

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

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

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
end

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

Cucumber
# In e.g. features/support/mocha.rb
require 'mocha/api'

World(Mocha::API)

Around do |scenario, block|
  begin
    mocha_setup
    block.call
    mocha_verify
  ensure
    mocha_teardown
  end
end

Rails

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.

Minitest

Note that since Rails v4 (at least), ActiveSupport::TestCase has inherited from Minitest::Test or its earlier equivalents. Thus unless you are explicitly using Test::Unit, you are likely to be using Minitest.

# Gemfile in Rails app
gem 'mocha'

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

Follow the instructions for the relevant test framework in the Bundler section, but ensure that the relevant Mocha file (mocha/minitest, mocha/test_unit, or mocha/api) is required after the test framework has been loaded, e.g. at the bottom of test_helper.rb or spec_helper.rb, or at least after rails/test_help has been required.

Known Issues

  • In Mocha v1.10.0 an undocumented feature of API#mock, API#stub & API#stub_everything was changed. Previously when these methods were passed a single symbol, they returned a mock object that responded to the method identified by the symbol. Now Passing a single symbol is equivalent to passing a single string, i.e. it now defines the 'name' of the mock object.
  • 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.

Usage

Quick Start

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

class MiscExampleTest < Test::Unit::TestCase
  def test_mocking_a_class_method
    product = Product.new
    Product.expects(:find).with(1).returns(product)
    assert_equal product, Product.find(1)
  end

  def test_mocking_an_instance_method_on_a_real_object
    product = Product.new
    product.expects(:save).returns(true)
    assert product.save
  end

  def test_stubbing_instance_methods_on_real_objects
    prices = [stub(pence: 1000), stub(pence: 2000)]
    product = Product.new
    product.stubs(:prices).returns(prices)
    assert_equal [1000, 2000], product.prices.collect {|p| p.pence}
  end

  def test_stubbing_an_instance_method_on_all_instances_of_a_class
    Product.any_instance.stubs(:name).returns('stubbed_name')
    product = Product.new
    assert_equal 'stubbed_name', product.name
  end

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

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

Mock Objects

class Enterprise
  def initialize(dilithium)
    @dilithium = dilithium
  end

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

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 = Enterprise.new(dilithium)
    enterprise.go(2)
  end
end

Partial Mocking

class Order
  attr_accessor :shipped_on

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

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

  def shipping_cost
    total_weight * 5 + 10
  end

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

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

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

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 = Order.new
    order.stubs(:total_weight).returns(10)
    assert_equal 60, order.shipping_cost
  end

  # illustrates stubbing class method
  def test_should_count_number_of_orders_shipped_after_specified_date
    now = Time.now; week_in_secs = 7 * 24 * 60 * 60
    order_1 = Order.new; order_1.shipped_on = now - 1 * week_in_secs
    order_2 = Order.new; 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)
  end

  # illustrates stubbing instance method for all instances of a class
  def test_should_calculate_value_of_unshipped_orders
    Order.stubs(:find_all).returns([Order.new, Order.new, Order.new])
    Order.any_instance.stubs(:shipped_on).returns(nil)
    Order.any_instance.stubs(:total_cost).returns(10)
    assert_equal 30, Order.unshipped_value
  end
end

Thread safety

Mocha currently does not attempt to be thread-safe.

Can I test multi-threaded code with Mocha?

The short answer is no. 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.

Can I run my tests across multiple threads?

Maybe, but probably not. 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. So, for example, if two tests are running concurrently and one uses #any_instance to modify a class, both tests will see those changes immediately.

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.

Configuration

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.

MOCHA_OPTIONS

MOCHA_OPTIONS is an environment variable whose value can be set to a comma-separated list, so that we can specify multiple options e.g. MOCHA_OPTIONS=debug,use_test_unit_gem. Only the following values are currently recognized and have an effect:

  • debug: Enables a debug mode which will output backtraces for each deprecation warning. This is useful for finding where in the test suite the deprecated calls are.

Semantic versioning

  • Every effort is made to comply with semantic versioning.
  • However, this only applies to the behaviour documented in the public API.
  • The documented public API does not include the content or format of messsages displayed to the user, e.g. assertion failure messages.

Useful Links

Contributors

See this list of contributors.

Releasing a new version

$ MOCHA_GENERATE_DOCS=true bundle install

$ MOCHA_GENERATE_DOCS=true rake generate_docs
$ curl -u <email-address> -H 'OTP:<one-time-password>' https://rubygems.org/api/v1/api_key.yaml > ~/.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 rubygems.org.

History

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

License

Β© Copyright James Mead 2006

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

More Repositories

1

oauth2-provider

An OAuth2 Provider for Rack-based apps (deprecated/not supported)
Ruby
110
star
2

method_log

Trace the history of an individual method in a git repository (experimental)
Ruby
70
star
3

jam-coop

A platform co-operative for musicians and fans
Ruby
53
star
4

ais-on-sdr

Ruby
21
star
5

bank

An exploration of how to create a simple "bank" in the UK in c. 2014
15
star
6

google-drive-backup

Scheduled backup of Google Drive to AWS S3 bucket using rclone sync
TypeScript
15
star
7

goos-ruby

The example from "Growing Object-Oriented Software, Guided by Tests" written in Ruby
Ruby
9
star
8

freerange-puppet

Ruby
7
star
9

site

Go Free Range website
Ruby
7
star
10

free_agent

A small ruby library for accessing information from http://freeagentcentral.com
Ruby
4
star
11

harmonia-old

The precursor to Harmonia.io, here for posterity only.
Ruby
4
star
12

deploy

Enables simple git-based deployments to freerange-compatible hosts
Ruby
3
star
13

nodetest

A simple unit testing framework that's sympathetic to node.js
3
star
14

contracts

Standard contracts that we use
3
star
15

trello-reports

Ruby scripts for generating reports for a Trello board
Ruby
3
star
16

webhooks

Bi-directional integration between Harmonia & Trello
Ruby
2
star
17

aldermore-bank-to-freeagent

Reformat Aldermore Bank CSV to be suitable for upload to FreeAgent banking
JavaScript
2
star
18

heroku-cedar-em-resque-polling

Ruby
2
star
19

pair-programming-presentation

A presentation about Pair Programming
2
star
20

test_startup

Startup and shutdown methods for test/unit or shoulda in Ruby 1.8
Ruby
2
star
21

temporary

Testing moving a repository and all its bits to an organisation account.
Ruby
2
star
22

hashblue-gem

A gem to access the hashblue API
Ruby
2
star
23

printer-bookmarks

A demonstration bookmark service for Printer
Ruby
2
star
24

hashblue-api-client

An example #blue API client
Ruby
2
star
25

freeagent_transaction_explainer

A Chrome Extension which helps explain bank transactions in FreeAgent
HTML
2
star
26

cotech-github-demo

How to add a new cooperative to the Jekyll version of the CoTech website (deprecated)
1
star
27

freerange-cli

Simple command line tools used by FreeRange
Ruby
1
star
28

flexmock-with-minitest

Demo of Flexmock/MiniTest integration
Ruby
1
star
29

iamdoingx

A native mac application to post a status update to PW
Objective-C
1
star
30

flexmock-with-testunit

Demo of FlexMock/Test::Unit integration
Ruby
1
star
31

request-db-dashboard

A dashboard viewer of data analyzed from request-log-analyzer
Ruby
1
star
32

jQuery-ChronoClass

jQuery plugin to add classes to elements depending on the time of day
JavaScript
1
star
33

cotech-website

Spike on Jekyll version of CoTech website (deprecated)
JavaScript
1
star
34

free_agent_sanity_check

This respository is DEPRECATED. See README for an explanation.
Ruby
1
star
35

freerange-beards

Go Free Range team hirsuteness
Ruby
1
star
36

rr-with-testunit

Demo of RR/Test::Unit integration
Ruby
1
star
37

sauron

The All Seeing Eye
Ruby
1
star
38

heroku-cedar-em-http-server

Ruby
1
star
39

rr-with-minitest

Demo of RR/MiniTest integration
Ruby
1
star
40

alexa-helper

A simple example Amazon Alexa handler written in JS and deployed to AWS Lambda using Serverless
JavaScript
1
star
41

action_controller_template_assertions_ticket_5247

Monkey patching action controller to fix rails lighthouse ticket 5247
Ruby
1
star
42

trello-backup

Backup Trello boards to S3 bucket
TypeScript
1
star
43

coop-model-documents

HTML translation of Co-operatives UK model governing documents
HTML
1
star