Class: Minicrest::IsCloseTo

Inherits:
Matcher
  • Object
show all
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.

Examples:

Basic usage

is_close_to(3.14, 0.01).matches?(3.14159)  # => true
is_close_to(3.14, 0.01).matches?(3.2)      # => false

With integers

is_close_to(100, 5).matches?(102)  # => true

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(expected, delta) ⇒ IsCloseTo

Creates a new close-to matcher.

Parameters:

  • expected (Numeric)

    the expected value

  • delta (Numeric)

    the acceptable difference



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

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



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.

Parameters:

  • actual (Numeric)

    the value that was checked

Returns:

  • (String)

    failure message showing actual difference



44
45
46
47
48
49
# File 'lib/minicrest/is_close_to.rb', line 44

def failure_message(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.

Parameters:

  • actual (Numeric)

    the value to check

Returns:

  • (Boolean)

    true if |actual - expected| <= delta



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.

Parameters:

  • actual (Numeric)

    the value that was checked

Returns:

  • (String)

    message indicating unexpected closeness



55
56
57
58
59
# File 'lib/minicrest/is_close_to.rb', line 55

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect} not to be close to #{@expected.inspect} (within #{@delta.inspect}), but it was
  MSG
end