{"id":13878497,"url":"https://github.com/freerange/mocha","last_synced_at":"2025-05-10T12:07:28.171Z","repository":{"id":437817,"uuid":"59509","full_name":"freerange/mocha","owner":"freerange","description":"A mocking and stubbing library for Ruby","archived":false,"fork":false,"pushed_at":"2025-03-01T17:09:40.000Z","size":4501,"stargazers_count":1248,"open_issues_count":111,"forks_count":160,"subscribers_count":25,"default_branch":"main","last_synced_at":"2025-05-08T23:44:09.445Z","etag":null,"topics":["minitest","mock","ruby","stub","test-unit","testing"],"latest_commit_sha":null,"homepage":"https://mocha.jamesmead.org","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/freerange.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"COPYING.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"floehopper"}},"created_at":"2008-10-04T13:34:25.000Z","updated_at":"2025-04-16T13:29:57.000Z","dependencies_parsed_at":"2024-01-01T15:31:55.392Z","dependency_job_id":"fc9306c6-7892-4d65-ab6d-6d48a3ec9b02","html_url":"https://github.com/freerange/mocha","commit_stats":{"total_commits":1792,"total_committers":69,"mean_commits":"25.971014492753625","dds":0.1808035714285714,"last_synced_commit":"b04143e13854d302b255b826220f2d950fa1fe0f"},"previous_names":[],"tags_count":90,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freerange%2Fmocha","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freerange%2Fmocha/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freerange%2Fmocha/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/freerange%2Fmocha/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/freerange","download_url":"https://codeload.github.com/freerange/mocha/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253381605,"owners_count":21899737,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["minitest","mock","ruby","stub","test-unit","testing"],"created_at":"2024-08-06T08:01:51.537Z","updated_at":"2025-05-10T12:07:28.145Z","avatar_url":"https://github.com/freerange.png","language":"Ruby","funding_links":["https://github.com/sponsors/floehopper"],"categories":["Ruby","Gems","Testing"],"sub_categories":["Testing"],"readme":"## Mocha [![CircleCI status of freerange/mocha](https://circleci.com/gh/freerange/mocha.svg?style=shield)](https://app.circleci.com/pipelines/github/freerange/mocha) [![Gem Version](https://badge.fury.io/rb/mocha.svg)](http://badge.fury.io/rb/mocha)\n\n### Description\n\n* A Ruby library for [mocking](http://xunitpatterns.com/Mock%20Object.html) and [stubbing](http://xunitpatterns.com/Test%20Stub.html) - but deliberately not (yet) [faking](http://xunitpatterns.com/Fake%20Object.html) or [spying](http://xunitpatterns.com/Test%20Spy.html).\n* A unified, simple and readable syntax for both full \u0026 partial mocking.\n* Built-in support for Minitest and Test::Unit.\n* Supported by many other test frameworks.\n\n### Intended Usage\n\nMocha is intended to be used in unit tests for the [Mock Object](http://xunitpatterns.com/Mock%20Object.html) or [Test Stub](http://xunitpatterns.com/Test%20Stub.html) types of [Test Double](http://xunitpatterns.com/Test%20Double.html), not the [Fake Object](http://xunitpatterns.com/Fake%20Object.html) or [Test Spy](http://xunitpatterns.com/Test%20Spy.html) 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.\n\n### Installation\n\n#### Gem\n\nInstall the latest version of the gem with the following command...\n\n    $ gem install mocha\n\nNote: If you are intending to use Mocha with Test::Unit or Minitest, you should only setup Mocha *after* loading the relevant test library...\n\n##### Test::Unit\n\n```ruby\nrequire 'rubygems'\ngem 'mocha'\nrequire 'test/unit'\nrequire 'mocha/test_unit'\n```\n\n##### Minitest\n\n```ruby\nrequire 'rubygems'\ngem 'mocha'\nrequire 'minitest/autorun'\nrequire 'mocha/minitest'\n```\n\n#### Bundler\n\nIf you're using Bundler, include Mocha in the `Gemfile` and then setup Mocha later once you know the test library has been loaded...\n\n##### Test::Unit\n\n```ruby\n# Gemfile\ngem 'mocha'\n\n# Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'`\nrequire 'test/unit'\nrequire 'mocha/test_unit'\n```\n\n##### Minitest\n\n```ruby\n# Gemfile\ngem 'mocha'\n\n# Elsewhere after Bundler has loaded gems e.g. after `require 'bundler/setup'`\nrequire 'minitest/autorun'\nrequire 'mocha/minitest'\n```\n\n##### RSpec\n\nRSpec includes a mocha adapter. Just tell RSpec you want to mock with `:mocha`:\n\n```ruby\n# Gemfile in Rails app\ngem 'mocha'\n\n# Within `spec/spec_helper.rb`\nRSpec.configure do |config|\n  config.mock_with :mocha\nend\n```\n\nNote: There is no need to use a require statement to setup Mocha; RSpec does this itself.\n\n##### Cucumber\n\n```ruby\n# In e.g. features/support/mocha.rb\nrequire 'mocha/api'\n\nWorld(Mocha::API)\n\nAround do |scenario, block|\n  begin\n    mocha_setup\n    block.call\n    mocha_verify\n  ensure\n    mocha_teardown\n  end\nend\n```\n\n#### Rails\n\nIf 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`.\n\n##### Minitest\n\nNote 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.\n\n```ruby\n# Gemfile in Rails app\ngem 'mocha'\n\n# At bottom of test_helper.rb (or at least after `require 'rails/test_help'`)\nrequire 'mocha/minitest'\n```\n\n##### Other Test Framework\n\nFollow the instructions for the relevant test framework in the [Bundler](#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.\n\n#### Known Issues\n\n* Prior to v1.15.0 (when support for Ruby v1.8 was dropped), 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 v1.8. See `test/acceptance/stub_method_defined_on_module_and_aliased_test.rb` for an example of this behaviour.\n\n### Usage\n\n#### Quick Start\n\n```ruby\nrequire 'test/unit'\nrequire 'mocha/test_unit'\n\nclass MiscExampleTest \u003c Test::Unit::TestCase\n  def test_mocking_a_class_method\n    product = Product.new\n    Product.expects(:find).with(1).returns(product)\n    assert_equal product, Product.find(1)\n  end\n\n  def test_mocking_an_instance_method_on_a_real_object\n    product = Product.new\n    product.expects(:save).returns(true)\n    assert product.save\n  end\n\n  def test_stubbing_instance_methods_on_real_objects\n    prices = [stub(pence: 1000), stub(pence: 2000)]\n    product = Product.new\n    product.stubs(:prices).returns(prices)\n    assert_equal [1000, 2000], product.prices.collect {|p| p.pence}\n  end\n\n  def test_stubbing_an_instance_method_on_all_instances_of_a_class\n    Product.any_instance.stubs(:name).returns('stubbed_name')\n    product = Product.new\n    assert_equal 'stubbed_name', product.name\n  end\n\n  def test_traditional_mocking\n    object = mock('object')\n    object.expects(:expected_method).with(:p1, :p2).returns(:result)\n    assert_equal :result, object.expected_method(:p1, :p2)\n  end\n\n  def test_shortcuts\n    object = stub(method1: :result1, method2: :result2)\n    assert_equal :result1, object.method1\n    assert_equal :result2, object.method2\n  end\nend\n```\n\n#### Mock Objects\n\n```ruby\nclass Enterprise\n  def initialize(dilithium)\n    @dilithium = dilithium\n  end\n\n  def go(warp_factor)\n    warp_factor.times { @dilithium.nuke(:anti_matter) }\n  end\nend\n\nrequire 'test/unit'\nrequire 'mocha/test_unit'\n\nclass EnterpriseTest \u003c Test::Unit::TestCase\n  def test_should_boldly_go\n    dilithium = mock()\n    dilithium.expects(:nuke).with(:anti_matter).at_least_once  # auto-verified at end of test\n    enterprise = Enterprise.new(dilithium)\n    enterprise.go(2)\n  end\nend\n```\n\n#### Partial Mocking\n\n```ruby\nclass Order\n  attr_accessor :shipped_on\n\n  def total_cost\n    line_items.inject(0) { |total, line_item| total + line_item.price } + shipping_cost\n  end\n\n  def total_weight\n    line_items.inject(0) { |total, line_item| total + line_item.weight }\n  end\n\n  def shipping_cost\n    total_weight * 5 + 10\n  end\n\n  class \u003c\u003c self\n    def find_all\n      # Database.connection.execute('select * from orders...\n    end\n\n    def number_shipped_since(date)\n      find_all.select { |order| order.shipped_on \u003e date }.length\n    end\n\n    def unshipped_value\n      find_all.inject(0) { |total, order| order.shipped_on ? total : total + order.total_cost }\n    end\n  end\nend\n\nrequire 'test/unit'\nrequire 'mocha/test_unit'\n\nclass OrderTest \u003c Test::Unit::TestCase\n  # illustrates stubbing instance method\n  def test_should_calculate_shipping_cost_based_on_total_weight\n    order = Order.new\n    order.stubs(:total_weight).returns(10)\n    assert_equal 60, order.shipping_cost\n  end\n\n  # illustrates stubbing class method\n  def test_should_count_number_of_orders_shipped_after_specified_date\n    now = Time.now; week_in_secs = 7 * 24 * 60 * 60\n    order_1 = Order.new; order_1.shipped_on = now - 1 * week_in_secs\n    order_2 = Order.new; order_2.shipped_on = now - 3 * week_in_secs\n    Order.stubs(:find_all).returns([order_1, order_2])\n    assert_equal 1, Order.number_shipped_since(now - 2 * week_in_secs)\n  end\n\n  # illustrates stubbing instance method for all instances of a class\n  def test_should_calculate_value_of_unshipped_orders\n    Order.stubs(:find_all).returns([Order.new, Order.new, Order.new])\n    Order.any_instance.stubs(:shipped_on).returns(nil)\n    Order.any_instance.stubs(:total_cost).returns(10)\n    assert_equal 30, Order.unshipped_value\n  end\nend\n```\n\n### Thread safety\n\nMocha currently *does not* attempt to be thread-safe.\n\n#### Can I test multi-threaded code with Mocha?\n\nThe 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.\n\n#### Can I run my tests across multiple threads?\n\nMaybe, 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.\n\n### Expectation matching / invocation order\n\nStubs 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.\n\nWhen 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. If the expectation that matches the invocation has a cardinality of \"never\", then an unexpected invocation error is reported.\n\nSee the [documentation](https://mocha.jamesmead.org/Mocha/Mock.html) for `Mocha::Mock` for further details.\n\n### Configuration\n\nIf you want, Mocha can generate a warning or raise an exception when:\n\n* stubbing a method unnecessarily\n* stubbing method on a non-mock object\n* stubbing a non-existent method\n* stubbing a non-public method\n\nSee the [documentation](https://mocha.jamesmead.org/Mocha/Configuration.html) for `Mocha::Configuration` for further details.\n\n### Debugging\n\nMocha provides some extra output to help with debugging when the standard Ruby debug option (`-d`) is set.\n\n### Semantic versioning\n\n* Every effort is made to comply with [semantic versioning](https://semver.org/).\n* However, this only applies to the behaviour documented in the public API.\n* The documented public API does *not* include the content or format of messsages displayed to the user, e.g. assertion failure messages.\n\n### Useful Links\n\n* [Official Documentation](https://mocha.jamesmead.org)\n* [Source Code](http://github.com/freerange/mocha)\n* [Mailing List](http://groups.google.com/group/mocha-developer)\n* [James Mead's Blog](http://jamesmead.org/blog/)\n* [An Introduction To Mock Objects In Ruby](http://jamesmead.org/talks/2007-07-09-introduction-to-mock-objects-in-ruby-at-lrug/)\n* [Mocks Aren't Stubs](http://martinfowler.com/articles/mocksArentStubs.html)\n* [Growing Object-Oriented Software Guided By Tests](http://www.growing-object-oriented-software.com/)\n* [Mock Roles Not Objects](http://www.jmock.org/oopsla2004.pdf)\n* [jMock](http://www.jmock.org/)\n\n### Contributors\n\nSee this [list of contributors](https://github.com/freerange/mocha/graphs/contributors).\n\n### Releasing a new version\n\n* Update the RELEASE.md file with a summary of changes\n* Bump the version in `lib/mocha/version.rb`\n* Commit \u0026 push to GitHub\n* Check CircleCI build is passing - https://app.circleci.com/pipelines/github/freerange/mocha\n\n* Generate documentation:\n\n```bash\n$ MOCHA_GENERATE_DOCS=true bundle install\n\n$ MOCHA_GENERATE_DOCS=true rake generate_docs\n```\n* Commit documentation \u0026 push to GitHub\n* Sign in to rubygems.org and find API key - https://rubygems.org/profile/edit\n\n```bash\n$ curl -u \u003cemail-address\u003e -H 'OTP:\u003cone-time-password\u003e' https://rubygems.org/api/v1/api_key.yaml \u003e ~/.gem/credentials; chmod 0600 ~/.gem/credentials\n```\n\n* Release gem to Rubygems:\n\n```bash\n$ rake release\n[runs tests]\nmocha 1.2.0 built to pkg/mocha-1.2.0.gem.\nTagged v1.2.0.\nPushed git commits and tags.\nPushed mocha 1.2.0 to rubygems.org.\n```\n\n### History\n\nMocha was initially harvested from projects at [Reevoo](http://www.reevoo.com/). It's syntax is heavily based on that of [jMock](http://www.jmock.org).\n\n### License\n\n\u0026copy; Copyright James Mead 2006\n\nYou may use, copy and redistribute this library under the same terms as [Ruby itself](https://www.ruby-lang.org/en/about/license.txt) or under the [MIT license](https://mit-license.org/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffreerange%2Fmocha","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffreerange%2Fmocha","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffreerange%2Fmocha/lists"}