Class: Minicrest::IsCloseTo
- Defined in:
- lib/minicrest/is_close_to.rb
Overview
Matcher that checks if a numeric value is within a delta of an expected value.
Useful for floating-point comparisons where exact equality is unreliable.
Instance Method Summary collapse
-
#description ⇒ String
Returns a description of what this matcher expects.
-
#failure_message(actual) ⇒ String
Returns the failure message when the match fails.
-
#initialize(expected, delta) ⇒ IsCloseTo
constructor
Creates a new close-to matcher.
-
#matches?(actual) ⇒ Boolean
Checks if actual is within delta of expected.
-
#negated_failure_message(actual) ⇒ String
Returns the failure message when a negated match fails.
Methods inherited from Matcher
Constructor Details
#initialize(expected, delta) ⇒ IsCloseTo
Creates a new close-to matcher.
19 20 21 22 23 |
# File 'lib/minicrest/is_close_to.rb', line 19 def initialize(expected, delta) super() @expected = expected @delta = delta end |
Instance Method Details
#description ⇒ String
Returns a description of what this matcher expects.
36 37 38 |
# File 'lib/minicrest/is_close_to.rb', line 36 def description "close to #{@expected.inspect} (within #{@delta.inspect})" end |
#failure_message(actual) ⇒ String
Returns the failure message when the match fails.
44 45 46 47 48 49 |
# File 'lib/minicrest/is_close_to.rb', line 44 def (actual) difference = (actual - @expected).abs <<~MSG.chomp expected #{actual.inspect} to be close to #{@expected.inspect} (within #{@delta.inspect}), but difference was #{difference.round(10)} MSG end |
#matches?(actual) ⇒ Boolean
Checks if actual is within delta of expected.
29 30 31 |
# File 'lib/minicrest/is_close_to.rb', line 29 def matches?(actual) (actual - @expected).abs <= @delta end |
#negated_failure_message(actual) ⇒ String
Returns the failure message when a negated match fails.
55 56 57 58 59 |
# File 'lib/minicrest/is_close_to.rb', line 55 def (actual) <<~MSG.chomp expected #{actual.inspect} not to be close to #{@expected.inspect} (within #{@delta.inspect}), but it was MSG end |