{"id":14991266,"url":"https://github.com/test-prof/mock-suey","last_synced_at":"2025-04-12T03:30:58.277Z","repository":{"id":63821745,"uuid":"566473853","full_name":"test-prof/mock-suey","owner":"test-prof","description":"Keeping mocks in line with real objects 🥡","archived":false,"fork":false,"pushed_at":"2023-05-01T11:47:18.000Z","size":179,"stargazers_count":50,"open_issues_count":1,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-05T13:17:06.018Z","etag":null,"topics":["mocks","rbs","rspec","testing"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/test-prof.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.txt","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":"test-prof"}},"created_at":"2022-11-15T18:46:52.000Z","updated_at":"2025-01-26T16:41:26.000Z","dependencies_parsed_at":"2024-09-25T00:34:33.444Z","dependency_job_id":null,"html_url":"https://github.com/test-prof/mock-suey","commit_stats":{"total_commits":18,"total_committers":2,"mean_commits":9.0,"dds":0.05555555555555558,"last_synced_commit":"1ff02ec0452d5e2120a9059deb0af1dea7806f72"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/test-prof%2Fmock-suey","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/test-prof%2Fmock-suey/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/test-prof%2Fmock-suey/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/test-prof%2Fmock-suey/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/test-prof","download_url":"https://codeload.github.com/test-prof/mock-suey/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248512497,"owners_count":21116613,"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":["mocks","rbs","rspec","testing"],"created_at":"2024-09-24T14:22:03.582Z","updated_at":"2025-04-12T03:30:57.615Z","avatar_url":"https://github.com/test-prof.png","language":"Ruby","funding_links":["https://github.com/sponsors/test-prof"],"categories":[],"sub_categories":[],"readme":"[![Gem Version](https://badge.fury.io/rb/mock-suey.svg)](https://rubygems.org/gems/mock-suey) [![Build](https://github.com/test-prof/mock-suey/workflows/Build/badge.svg)](https://github.com/test-prof/mock-suey/actions)\n\n# Mock Suey\n\n\u003cimg align=\"right\" height=\"168\" width=\"120\"\n     title=\"Mock Suey logo\" src=\"./assets/logo.png\"\u003e\n\nA collection of tools to keep mocks in line with real objects.\n\n\u003e Based on the RubyConf 2022 talk [\"Weaving and seaming mocks\"][the-talk]\n\n## Table of contents\n\n- [Installation](#installation)\n- [Typed doubles](#typed-doubles)\n  - [Using with RBS](#using-with-rbs)\n  - [Typed doubles limitations](#typed-doubles-limitations)\n- [Mock context](#mock-context)\n- [Auto-generated type signatures and post-run checks](#auto-generated-type-signatures-and-post-run-checks)\n- [Mock contracts verification](#mock-contracts-verification)\n- [Tracking stubbed method calls](#tracking-stubbed-method-calls)\n- [Tracking real method calls](#tracking-real-method-calls)\n- [Configuration](#configuration)\n- [Future development](#future-development)\n\n## Installation\n\n```ruby\n# Gemfile\ngroup :test do\n  gem \"mock-suey\"\nend\n```\n\nThen, drop `\"require 'mock-suey'` to your `spec_helper.rb` / `rails_helper.rb` / `whatever_helper.rb`.\n\n## Typed doubles\n\nMockSuey enhances verified doubles by adding type-checking support: every mocked method call is checked against the corresponding method signature (if present), and an exception is raised if types mismatch.\n\nConsider an example:\n\n```ruby\nlet(:array_double) { instance_double(\"Array\") }\n\nspecify \"#take\" do\n  allow(array_double).to receive(:take).and_return([1, 2, 3])\n\n  expect(array_double.take(\"three\")).to eq([1, 2, 3])\nend\n```\n\nThis test passes with plain RSpec, because from the verified double perspective everything is valid. However, calling `[].take(\"string\")` raises a TypeError in runtime.\n\nWith MockSuey and [RBS][rbs], we can make verified doubles stricter and ensure that the types we use in method stubs are correct.\n\nTo enable typed verified doubles, you must explicitly configure a type checker.\n\n### Using with RBS\n\n**NOTE:** RBS 3.0+ is not supported yet. We're working on it.\n\nTo use MockSuey with RBS, configure it as follows:\n\n```ruby\nMockSuey.configure do |config|\n  config.type_check = :ruby\n  # Optional: specify signature directries to use (\"sig\" is used by default)\n  # config.signature_load_dirs = [\"sig\"]\n  # Optional: specify whether to raise an exception if no signature found\n  # config.raise_on_missing_types = false\nend\n```\n\nMake sure that `rbs` gem is present in the bundle (MockSuey doesn't require it as a runtime dependency).\n\nThat's it! Now all mocked methods are type-checked.\n\n### Typed doubles limitations\n\nTyped doubles rely on the type signatures being defined. What if you don't have types (or don't want to add them)? There are two options:\n\n1) Adding type signatures only for the objects being mocked. You don't even need to type check your code or cover it with types. Instead, you can rely on runtime checks made in tests for real objects and use typed doubles for mocked objects.\n\n2) Auto-generating types on-the-fly from the real call traces (see below).\n\n## Mock context\n\nMock context is a re-usable mocking/stubbing configuration. Keeping a _library of mocks_\nhelps to keep fake objects under control. The idea is similar to data fixtures (and heavily inspired by the [fixturama][] gem).\n\nTechnically, mock contexts are _shared contexts_ (in RSpec sense) that _know_ which objects and methods are being mocked at the boot time, not at the run time. We use this knowledge to collect calls made on _real_ objects (so we can use them for the mocked calls verification later).\n\n### Defining and including mock contexts\n\nThe API is similar to shared contexts:\n\n```ruby\n# Define a context\nRSpec.mock_context \"Anyway::Env\" do\n  let(:testo_env) do\n    {\n      \"a\" =\u003e \"x\",\n      \"data\" =\u003e {\n        \"key\" =\u003e \"value\"\n      }\n    }\n  end\n\n  before do\n    env_double = instance_double(\"Anyway::Env\")\n    allow(::Anyway::Env).to receive(:new).and_return(env_double)\n\n    allow(env_double).to receive(:fetch).with(\"UNKNOWN\", any_args).and_return(Anyway::Env::Parsed.new({}, nil))\n    allow(env_double).to receive(:fetch).with(\"TESTO\", any_args).and_return(Anyway::Env::Parsed.new(testo_env, nil))\n    allow(env_double).to receive(:fetch).with(\"\", any_args).and_return(nil)\n  end\nend\n\n# Include in a test file\ndescribe Anyway::Loaders::Env do\n  include_mock_context \"Anyway::Env\"\n\n  # ...\nend\n```\n\nIt's recommended to keep mock contexts under `spec/mocks` or `spec/fixtures/mocks` and load them in the RSpec configuration file:\n\n```ruby\nDir[\"#{__dir__}/mocks/**/*.rb\"].sort.each { |f| require f }\n```\n\n### Accessing mocked objects information\n\nYou can get the registry of mocked objects and methods after all tests were loaded,\nfor example, in the `before(:suite)` hook:\n\n```ruby\nRSpec.configure do |config|\n  config.before(:suite) do\n    MockSuey::RSpec::MockContext.registry.each do |klass, methods|\n      methods.each do |method_name, stub_calls|\n        # Stub calls is a method call object,\n        # containing the information about the stubbed call:\n        # - receiver_class == klass\n        # - method_name == method_name\n        # - arguments: expected arguments (empty if expects no arguments)\n        # - return_value: stubbed return value\n      end\n    end\n  end\nend\n```\n\n## Auto-generated type signatures and post-run checks\n\nWe can combine typed doubles and mock contexts to provide type-checking capabilities to codebase not using type signatures. For that, we can generate type signatures automatically by tracing _real_ object calls.\n\nYou must opt-in to use this feature:\n\n```ruby\nMockSuey.configure do |config|\n  # Make sure type checker is configured\n  config.type_check = :ruby\n  config.auto_type_check = true\n  # Choose the real objects tracing method\n  config.trace_real_calls_via = :prepend # or :trace_point\n  # Whether to raise if type is missing in a post-check\n  # (i.e., hasn't been generated)\n  config.raise_on_missing_auto_types = true\nend\n```\n\nUnder the hood, we use the [Tracking real method calls](#tracking-real-method-calls) feature described below.\n\n**IMPORTANT**: Only objects declared within mock contexts could be type-checked.\n\n### Limitations\n\nCurrently, this feature only works if both real objects and mock objects calls are made during the same test run. Thus, tests could fail when running tests in parallel.\n\n## Mock contracts verification\n\nTypes drastically increase mocks/stubs stability (or consistency), but even they do not guarantee that mocks behave the same way as real objects. For example, if your method returns completely different results depending on the values (not types) of the input.\n\nThe only way to provide ~100% confidence to mocks is enforcing a contract. One way to enforce mock contracts is to require having a unit/functional tests where a real object receives the same input and returns the same result as the mock. For example, consider the following tests:\n\n```ruby\ndescribe Accountant do\n  let(:calculator) { instance_double(\"TaxCalculator\") }\n\n  # Declaring a mock == declaring a contract (input/output correspondance)\n  before do\n    allow(calculator).to receive(:tax_for_income).with(2020).and_return(202)\n    allow(calculator).to receive(:tax_for_income).with(0).and_return(0)\n  end\n\n  subject { described_class.new(calculator) }\n\n  specify \"#after_taxes\" do\n    # Assuming the #after_taxes method calls calculator.tax_for_income\n    expect(subject.after_taxes(2020)).to eq(1818)\n    expect(subject.after_taxes(0)).to be_nil\n  end\nend\n\ndescribe TaxCalculator do\n  subject { described_class.new }\n\n  # Adding a unit-test using the same input\n  # verifies the contract\n  specify \"#tax_for_income\" do\n    expect(subject.tax_for_income(2020)).to eq(202)\n    expect(subject.tax_for_income(0)).to eq(0)\n  end\nend\n```\n\nWe need a way to enforce mock contract verification. In other words, if the dependency behaviour changes and the corresponding unit-test reflects this change, our mock should be marked as invalid and result into a test suit failure.\n\nOne way to do this is to introduce explicit contract verification (via custom mocking mechanisms or DSL or whatever, see [bogus][] or [compact][], for example).\n\nMock Suey chooses another way: automatically infer mock contracts (via mock contexts) and verify them by collecting real object calls during the test run. You can enable this feature via the following configuration options:\n\n```ruby\nMockSuey.configure do |config|\n  config.verify_mock_contracts = true\n  # Choose the real objects tracing method\n  config.trace_real_calls_via = :prepend # or :trace_point\nend\n```\n\nEach method stub represents a contract. For example:\n\n```ruby\nallow(calculator).to receive(:tax_for_income).with(2020).and_return(202)\nallow(calculator).to receive(:tax_for_income).with(0).and_return(0)\n\n#=\u003e TaxCalculator#tax_for_income: (2020) -\u003e Integer\n#=\u003e TaxCalculator#tax_for_income: (0) -\u003e Integer\n```\n\nIf the method behaviours changes, running tests would result in a failure if mock doesn't reflect the change:\n\n```ruby\n# Assuming we decided to return nil for non-positive integers\nspecify \"#tax_for_income\" do\n  expect(subject.tax_for_income(0)).to be_nil\nend\n```\n\nThe test suite will fail with the following exception:\n\n```sh\n$ rspec accountant_spec.rb\n\n........\n\n1) Mock contract verification failed:\n   No matching call found for:\n     TaxCalculator#tax_for_income: (0) -\u003e Integer\n   Captured calls:\n     (0) -\u003e NilClass\n```\n\nThe contract describes which explicit input values result in a particular output type (not value). Such verification can help to verify boundary conditions (e.g., when some inputs result in nil results or exceptions).\n\n### Limitations\n\n1. Currently, verification takes into account only primitive values (String, Number, Booleans, plain Ruby hashes and arrays, etc.). Custom classes are not yet supported.\n\n2. Similarly to auto-type checks, this feature does not yet support parallel tests execution.\n\n## Tracking stubbed method calls\n\nThe core functionality of this gem is the ability to hook into mocked method invocations to perform custom checks.\n\n**NOTE:** Currently, only RSpec is supported.\n\nYou can add an after mock call callback as follows:\n\n```ruby\nMockSuey.on_mocked_call do |call_obj|\n  # Do whatever you want with the method call object,\n  # containing the following fields:\n  # - receiver_class\n  # - method_name\n  # - arguments\n  # - return_value\nend\n```\n\nBy default, MockSuey doesn't keep mocked calls, but if you want to analyze them\nat the end of the test suite run, you can configure MockSuey to keep all the calls and\naccess them later:\n\n```ruby\nMockSuey.configure do |config|\n  config.store_mocked_calls = true\nend\n\n# Them, you can access them in the after(:suite) hook, for example\nRSpec.configure do |config|\n  config.after(:suite) do\n    p MockSuey.stored_mocked_calls\n  end\nend\n```\n\n## Tracking real method calls\n\nThis gem provides a method call tracking functionality for non-double objects.\nYou can use it separately (not as a part of auto-type-checking or contract verification features). For example:\n\n```ruby\nRSpec.configure do |config|\n  tracer = MockSuey::Tracer.new(via: :trace_point) # or via: :prepend\n\n  config.before(:suite) do\n    tracer.collect(SomeClass, %i[some_method another_method])\n    tracer.start!\n  end\n\n  config.after(:suite) do\n    calls = traces.stop\n    # where call is a call object\n    # similar to a mocked call object described above\n  end\nend\n```\n\n## Configuration\n\nAdditional configuration options could be set:\n\n```ruby\nMockSuey.configure do |config|\n  # A logger instance\n  config.logger = Logger.new($stdout)\n  # You can also specify log level and whether to colorize logs\n  # config.log_level = :info\n  # config.color = ? # Depends on the logging device\n  # Debug mode is a shortcut to setup an STDOUT logger with the debug level\n  config.debug = ENV[\"MOCK_SUEY_DEBUG\"] == \"true\" # or 1, y, yes, or t\nend\n```\n\n## Future development\n\nI'm interested in the following contributions/discussions:\n\n- Figure out parallel builds\n- Sorbet support\n- Minitest support\n- Advanced mock contracts (custom rules, custom classes support, etc.)\n- Methods delegation (e.g., `.perform_async -\u003e #perform`, `.call -\u003e #call`)\n- Exceptions support in contracts verification\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at [https://github.com/test-prof/mock-suey](https://github.com/palkan/mock-suey).\n\n## Credits\n\nThis gem is generated via [new-gem-generator](https://github.com/palkan/new-gem-generator).\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).\n\n[the-talk]: https://evilmartians.com/events/weaving-and-seaming-mocks\n[rbs]: https://github.com/ruby/rbs\n[fixturama]: https://github.com/nepalez/fixturama\n[bogus]: https://github.com/psyho/bogus\n[compact]: https://github.com/robwold/compact\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftest-prof%2Fmock-suey","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftest-prof%2Fmock-suey","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftest-prof%2Fmock-suey/lists"}