Class: Matchi::Change::Delta

Inherits:
Object
  • Object
show all
Defined in:
lib/matchi/change/delta.rb

Overview

Passes when the difference between the observed value after and before the block, after - before, is exactly the expected delta (:by), at least it (:by_at_least) or at most it (:by_at_most). The expected delta receives the comparison; the difference is computed by the observed values, so this matcher depends on their honesty.

Examples:

list = []
Matchi::Change::Delta.new(:by, 2) { list.length }.match? { list.push(1, 2) } # => true

Constant Summary collapse

KINDS =

For each kind: the comparison the delta receives, and its description.

{
  by:          [:==, "by"],
  by_at_least: [:<=, "by at least"],
  by_at_most:  [:>=, "by at most"]
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(kind, delta, &state) ⇒ Delta

Returns a new instance of Delta.

Parameters:

  • kind (Symbol) —

    :by, :by_at_least or :by_at_most

  • delta (Numeric) —

    a finite real number, non-negative unless kind is :by

Yield Returns:

  • (Object) —

    the observed value

Raises:

  • (ArgumentError) —

    when the kind is unknown, delta is not such a number, or no block is given



28
29
30
31
32
33
34
35
# File 'lib/matchi/change/delta.rb', line 28

def initialize(kind, delta, &state)
  raise ::ArgumentError, "unknown kind #{kind.inspect}" unless KINDS.key?(kind)
  raise ::ArgumentError, "a block must be provided" unless block_given?

  @operator, @label = KINDS.fetch(kind)
  @delta = kind == :by ? Number.finite_real!(delta, "delta") : Number.non_negative!(delta, "delta")
  @state = state
end

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    ignored, the block is evaluated for its effect

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given



40
41
42
43
44
45
46
47
48
# File 'lib/matchi/change/delta.rb', line 40

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

  value_before = @state.call
  yield
  value_after = @state.call

  @delta.public_send(@operator, value_after - value_before) ? true : false
end

#to_s ⇒ String

Returns:

  • (String)


51
52
53
# File 'lib/matchi/change/delta.rb', line 51

def to_s
  "change #{@label} #{@delta.inspect}"
end