Class: Matchi::BeWithin::Of

Inherits:
Object
  • Object
show all
Defined in:
lib/matchi/be_within/of.rb

Overview

*BeWithin of* matcher.

Instance Method Summary collapse

Constructor Details

#initialize(delta, expected) ⇒ Of

Initialize the matcher with a delta and an expected value.

Examples:

require "matchi/be_within/of"

Matchi::BeWithin::Of.new(1, 41)

Parameters:

  • delta (Numeric)

    The accepted variation of the actual value.

  • expected (Numeric)

    The expected value.

Raises:

  • (::ArgumentError)


16
17
18
19
20
21
22
23
# File 'lib/matchi/be_within/of.rb', line 16

def initialize(delta, expected)
  raise ::ArgumentError, "delta must be a Numeric" unless delta.is_a?(::Numeric)
  raise ::ArgumentError, "expected must be a Numeric" unless expected.is_a?(::Numeric)
  raise ::ArgumentError, "delta must be non-negative" if delta.negative?

  @delta    = delta
  @expected = expected
end

Instance Method Details

#match?Boolean

Boolean comparison on the expected be_within by comparing the actual value and the expected value.

Examples:

require "matchi/be_within/of"

matcher = Matchi::BeWithin::Of.new(1, 41)
matcher.match? { 42 } # => true

Yield Returns:

  • (Numeric)

    The block of code to execute.

Returns:

  • (Boolean)

    Comparison between the actual and the expected values.

Raises:

  • (::ArgumentError)


37
38
39
40
41
# File 'lib/matchi/be_within/of.rb', line 37

def match?
  raise ::ArgumentError, "a block must be provided" unless block_given?

  (@expected - yield).abs <= @delta
end

#to_sString

Returns a string representing the matcher.

Returns:

  • (String)

    a human-readable description of the matcher



46
47
48
# File 'lib/matchi/be_within/of.rb', line 46

def to_s
  "be within #{@delta} of #{@expected}"
end