Class: Ward::Matchers::CloseTo

Inherits:
Matcher
  • Object
show all
Defined in:
lib/ward/matchers/close_to.rb

Overview

Tests whether the validation value is within the delta of the expected value.

Examples:

Validating that the estimate attribute is 10 (+- 5).


class Price
  validate do |price|
    price.estimate.is.close_to(10, 5)
  end
end

Instance Attribute Summary

Attributes inherited from Matcher

#expected, #extra_args

Instance Method Summary collapse

Methods inherited from Matcher

error_id

Constructor Details

#initialize(expected, delta, *extra_args) ⇒ CloseTo

Creates a new CloseTo matcher instance.

Parameters:

  • expected (Numeric)

    The expected value for the matcher.

  • delta (Numeric)

    The the acceptable range by which the actual value can deviate.

Raises:

  • (ArgumentError)


23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ward/matchers/close_to.rb', line 23

def initialize(expected, delta, *extra_args)
  raise ArgumentError,
    'The CloseTo matcher requires that the +expected+ value ' \
    'responds to +-+' unless expected.respond_to?(:-)

  raise ArgumentError,
    'The CloseTo matcher requires that a Numeric +delta+ value ' \
    'is supplied' unless delta.kind_of?(Numeric)

  super(expected, *extra_args)

  @delta = delta
end

Instance Method Details

#customise_error_values(values) ⇒ String

Adds extra information to the error message.

Parameters:

  • error (String)

Returns:

  • (String)


53
54
55
56
# File 'lib/ward/matchers/close_to.rb', line 53

def customise_error_values(values)
  values[:delta] = @delta
  values
end

#matches?(actual) ⇒ Boolean

Returns whether the given value is close to the expected value.

Parameters:

  • actual (Object)

    The validation value.

Returns:

  • (Boolean)


44
45
46
# File 'lib/ward/matchers/close_to.rb', line 44

def matches?(actual)
  (actual - @expected).abs <= @delta
end