Class: Matchi::Change::ByAtMost
- Inherits:
-
Object
- Object
- Matchi::Change::ByAtMost
- Defined in:
- lib/matchi/change/by_at_most.rb
Overview
This matcher verifies maximum changes only. For exact changes, use By, and for minimum changes, use ByAtLeast.
Maximum delta matcher that verifies numeric changes don’t exceed a limit.
This matcher ensures that a numeric value changes by no more than the specified amount after executing a block of code. It’s particularly useful when testing operations where you want to enforce an upper bound on changes, such as rate limiting, resource consumption, or controlled increments.
Instance Method Summary collapse
-
#initialize(expected, &state) ⇒ ByAtMost
constructor
Initialize the matcher with a maximum allowed change and a state block.
-
#match? { ... } ⇒ Boolean
Checks if the value changes by no more than the expected amount.
-
#to_s ⇒ String
Returns a human-readable description of the matcher.
Constructor Details
#initialize(expected, &state) ⇒ ByAtMost
Initialize the matcher with a maximum allowed change and a state block.
114 115 116 117 118 119 120 121 |
# File 'lib/matchi/change/by_at_most.rb', line 114 def initialize(expected, &state) raise ::ArgumentError, "expected must be a Numeric" unless expected.is_a?(::Numeric) raise ::ArgumentError, "a block must be provided" unless block_given? raise ::ArgumentError, "expected must be non-negative" if expected.negative? @expected = expected @state = state end |
Instance Method Details
#match? { ... } ⇒ Boolean
Checks if the value changes by no more than the expected amount.
This method compares the value before and after executing the provided block, ensuring that the absolute difference is less than or equal to the expected maximum. This is useful for enforcing upper bounds on state changes.
147 148 149 150 151 152 153 154 155 |
# File 'lib/matchi/change/by_at_most.rb', line 147 def match? raise ::ArgumentError, "a block must be provided" unless block_given? value_before = @state.call yield value_after = @state.call @expected >= (value_after - value_before) end |
#to_s ⇒ String
Returns a human-readable description of the matcher.
166 167 168 |
# File 'lib/matchi/change/by_at_most.rb', line 166 def to_s "change by at most #{@expected.inspect}" end |