サンプル
minitest 5.25.4: Minitest::Mock verifies strict call counts, FIFO ordered expectations, and case-equality argument matches while Object#stub temporarily replaces existing methods with static or callable handlers
検証済みサンプル — gem minitest 5.25.4: Minitest::Mock verifies strict call counts, FIFO ordered expectations, and case-equality argument matches while Object#stub…
sha256:aa5aeb38ff0dab1a266451a6777af1b86bb9eb5438f00e4eaf123093ff790b4f
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 2
- ビルドした署名鍵
- 2
宣言された環境
ruby linux x64 ruby ruby bundler
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-17 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-18 |
ケース
HOW- ゴール
- Minitest::Mock verifies strict call counts, FIFO ordered expectations, and case-equality argument matches while Object#stub temporarily replaces existing methods with static or callable handlers
- パッケージ
- シンボル
-
- Minitest::Mock
- Minitest::Mock#expect
- Minitest::Mock#verify
- MockExpectationError
- Object#stub
- Minitest::Assertions#assert_mock
- 環境
- ruby
- 作成日
- 2026-08-17T13:53:35Z
コントラクト
- Minitest::Mock raises NoMethodError for unmocked calls, raises ArgumentError on argument count mismatch, validates argument types via case equality (===), and raises MockExpectationError on unmet expectations upon calling verify
- Multiple expect registrations for the same method name are consumed in FIFO order, raising MockExpectationError if called more times than registered
- Passing a block to Minitest::Mock#expect evaluates argument conditions at call time and raises MockExpectationError when the block returns false
- Object#stub replaces an existing method on any object for the duration of a block, forwarding arguments to callables or returning static values, and strictly restores the original method even when an exception is raised
- Minitest::Assertions#assert_mock delegates to Mock#verify and converts MockExpectationError into a test assertion failure
ファイル
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- test/contract.rb
ソース
source "https://rubygems.org"
gem "minitest", "= 5.25.4"
GEM
remote: https://rubygems.org/
specs:
minitest (5.25.4)
PLATFORMS
ruby
x64-mingw-ucrt
x86_64-linux
x86_64-linux-musl
DEPENDENCIES
minitest (= 5.25.4)
CHECKSUMS
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
minitest (5.25.4) sha256=9cf2cae25ac4dfc90c988ebc3b917f53c054978b673273da1bd20bcb0778f947
BUNDLED WITH
4.0.18
# Minitest Mock and Stub Behavior
## Known Solutions Search
A search with `search_known_solution` for `minitest` returned:
- `sha256:b46d09ac09a40810f24397605f05ee322446d0b080b89fbb246295977afede04` (Minitest 6.0.6 explicit assertion migrations and mock extractions)
- `sha256:0199365007f54358f8e7dc42e65dee893c7de0bcabb962584bf17d58e0e689b3` (Minitest parallel executor initialization and `MT_CPU` environment handling)
This project focuses on a distinct subsystem in the previous stable major: the built-in `Minitest::Mock` object verification mechanics and `Object#stub` method overriding lifecycle in `minitest` 5.25.4.
## Pinned Version
- `minitest`: `5.25.4`
## Observed Behavior
1. **Unmocked Invocations and Verification**:
- Calling an unmocked method on a `Minitest::Mock` instance immediately raises `NoMethodError` (`"unmocked method :symbol, expected one of [...]"`).
- Calling `verify` on a mock with unsatisfied expectations raises `MockExpectationError` with the description of the unfulfilled call (`"Expected method(args) => retval"`).
2. **FIFO Expectation Queuing and Exhaustion**:
- Multiple `expect` registrations for the same method name are queued and satisfied sequentially in first-in, first-out (FIFO) order.
- Calling a mocked method more times than registered raises `MockExpectationError` (`"No more expects available for :symbol"`).
3. **Argument Validation**:
- An argument count mismatch immediately raises `ArgumentError` (`"mocked method :symbol expects N arguments, got M"`).
- Argument values are matched using case equality (`===`), enabling type matching with classes (e.g. `Integer`) or patterns (e.g. `Regexp`). Value mismatches raise `MockExpectationError`.
4. **Dynamic Block Expectations**:
- When a block is passed to `Minitest::Mock#expect`, the block evaluates call arguments dynamically. Returning `false` or `nil` raises `MockExpectationError` (`"mocked method :symbol failed block w/ [...]"`).
5. **`Object#stub` Scoping and Cleanup**:
- `Object#stub(name, val_or_callable)` temporarily replaces an existing method on the receiver for the duration of the provided block. Stubbing a non-existent method raises `NameError`.
- When given a callable (such as a lambda or proc), arguments are forwarded to `#call`. When given a static value, that value is returned.
- The original method definition is restored in an `ensure` block, guaranteeing clean teardown even if an unhandled exception occurs inside the stub block.
6. **Assertion Integration**:
- `Minitest::Assertions#assert_mock(mock)` calls `mock.verify`, converting any `MockExpectationError` into an assertion failure (`Minitest::Assertion`) and incrementing assertion counts.
{"case":{"caseId":"case:sha256:b66fdb7895efbf617dd538ac59dc3cdcac4155a3a48ff2f4050b8621e6ee0f6c","contract":["Minitest::Mock raises NoMethodError for unmocked calls, raises ArgumentError on argument count mismatch, validates argument types via case equality (===), and raises MockExpectationError on unmet expectations upon calling verify","Multiple expect registrations for the same method name are consumed in FIFO order, raising MockExpectationError if called more times than registered","Passing a block to Minitest::Mock#expect evaluates argument conditions at call time and raises MockExpectationError when the block returns false","Object#stub replaces an existing method on any object for the duration of a block, forwarding arguments to callables or returning static values, and strictly restores the original method even when an exception is raised","Minitest::Assertions#assert_mock delegates to Mock#verify and converts MockExpectationError into a test assertion failure"],"goal":"Minitest::Mock verifies strict call counts, FIFO ordered expectations, and case-equality argument matches while Object#stub temporarily replaces existing methods with static or callable handlers","kind":"HOW","packages":["pkg:gem/minitest@5.25.4"],"schemaVersion":1,"symbols":["Minitest::Mock","Minitest::Mock#expect","Minitest::Mock#verify","MockExpectationError","Object#stub","Minitest::Assertions#assert_mock"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/minitest@5.25.4"],"schemaVersion":1,"symbols":["Minitest::Mock","Minitest::Mock#expect","Minitest::Mock#verify","MockExpectationError","Object#stub","Minitest::Assertions#assert_mock"],"verifierAdapter":"rubygems@1"}
require "bundler/setup"
require "minitest"
require "minitest/mock"
require "minitest/test"
raise "expected minitest 5.25.4" unless Minitest::VERSION == "5.25.4"
# 1. Unmocked calls raise NoMethodError, argument count mismatch raises ArgumentError,
# argument types are validated via case equality (===), and unfulfilled calls fail verify with MockExpectationError.
mock = Minitest::Mock.new
begin
mock.unregistered_method
raise "expected NoMethodError for unregistered method"
rescue NoMethodError => e
raise "unexpected unmocked error message: #{e.message}" unless e.message.include?("unmocked method :unregistered_method")
end
mock.expect(:fetch_record, { id: 101 }, [Integer, /^active_/])
begin
mock.fetch_record(101)
raise "expected ArgumentError on argument count mismatch"
rescue ArgumentError => e
raise "unexpected arg count error: #{e.message}" unless e.message.include?("expects 2 arguments, got [101]")
end
begin
mock.fetch_record(101, "archived_status")
raise "expected MockExpectationError on argument value mismatch"
rescue MockExpectationError => e
raise "unexpected mismatch error: #{e.message}" unless e.message.include?("unexpected arguments [101, \"archived_status\"]")
end
mock_unmet = Minitest::Mock.new
mock_unmet.expect(:mandatory_step, true, [String])
begin
mock_unmet.verify
raise "expected MockExpectationError on verify"
rescue MockExpectationError => e
raise "unexpected verify error: #{e.message}" unless e.message.include?("Expected mandatory_step(String) => true")
end
res = mock.fetch_record(42, "active_user")
raise "expected return value { id: 101 }" unless res == { id: 101 }
raise "expected verify to succeed" unless mock.verify == true
# 2. Multiple expect registrations on the same method are matched in FIFO order and raise when exhausted.
fifo_mock = Minitest::Mock.new
fifo_mock.expect(:next_state, :queued)
fifo_mock.expect(:next_state, :running)
fifo_mock.expect(:next_state, :done)
raise "expected state :queued" unless fifo_mock.next_state == :queued
raise "expected state :running" unless fifo_mock.next_state == :running
raise "expected state :done" unless fifo_mock.next_state == :done
raise "expected verify true" unless fifo_mock.verify == true
begin
fifo_mock.next_state
raise "expected MockExpectationError on exhausted expectations"
rescue MockExpectationError => e
raise "unexpected exhausted error: #{e.message}" unless e.message.include?("No more expects available for :next_state")
end
# 3. Passing a block to expect validates arguments dynamically and raises MockExpectationError if falsey.
block_mock = Minitest::Mock.new
block_mock.expect(:apply_discount, 50) do |amount, percent|
amount > 0 && percent >= 0 && percent <= 100
end
begin
block_mock.apply_discount(-10, 20)
raise "expected MockExpectationError on failing block predicate"
rescue MockExpectationError => e
raise "unexpected block error: #{e.message}" unless e.message.include?("failed block")
end
block_mock_success = Minitest::Mock.new
block_mock_success.expect(:apply_discount, 50) do |amount, percent|
amount > 0 && percent >= 0 && percent <= 100
end
raise "expected discount 50" unless block_mock_success.apply_discount(100, 20) == 50
raise "expected block_mock verify true" unless block_mock_success.verify == true
# 4. Object#stub replaces existing methods with static or callable values and restores on exit/exception.
target = "sample payload"
# Stubbing an undefined method raises NameError
begin
target.stub(:non_existent_method, "val") {}
raise "expected NameError when stubbing undefined method"
rescue NameError => e
raise "unexpected NameError message: #{e.message}" unless e.message.include?("undefined method")
end
# Static return value replacement
res_stub = target.stub(:length, 999) do
target.length
end
raise "expected stubbed length 999" unless res_stub == 999
raise "expected restored length 14" unless target.length == 14
# Callable lambda receiving forwarded arguments
target.stub(:split, ->(pattern) { ["part_a", "part_b"] }) do
raise "expected stubbed split" unless target.split(" ") == ["part_a", "part_b"]
end
raise "expected restored split" unless target.split(" ") == ["sample", "payload"]
# Guarantee of restoration even when an exception occurs inside the block
begin
target.stub(:upcase, "TEMPORARY") do
raise RuntimeError, "simulated failure inside stub block"
end
rescue RuntimeError => e
raise "unexpected exception" unless e.message == "simulated failure inside stub block"
raise "expected upcase restored after exception" unless target.upcase == "SAMPLE PAYLOAD"
end
# 5. Minitest::Assertions#assert_mock verifies mock and turns failure into assertion flunk.
assertion_context = Class.new do
include Minitest::Assertions
attr_accessor :assertions
def initialize
@assertions = 0
end
end.new
passing_mock = Minitest::Mock.new
passing_mock.expect(:ack, true)
passing_mock.ack
assertion_context.assert_mock(passing_mock)
raise "expected assertion count to increment" unless assertion_context.assertions == 1
failing_mock = Minitest::Mock.new
failing_mock.expect(:ack, true)
begin
assertion_context.assert_mock(failing_mock)
raise "expected assertion failure"
rescue Minitest::Assertion => e
raise "unexpected assertion message: #{e.message}" unless e.message.include?("Expected ack() => true")
end