Sha256: 2643cb7f463227c1724f17f3ac9ae04bd3084fcf486a8b38722de17dd22ca384

Contents?: true

Size: 1.83 KB

Versions: 3

Compression:

Stored size: 1.83 KB

Contents

# frozen_string_literal: true

module Matchi
  class Change
    # *Change by at least* matcher.
    class ByAtLeast
      # Initialize the matcher with an object and a block.
      #
      # @example
      #   require "matchi/change/by_at_least"
      #
      #   object = []
      #
      #   Matchi::Change::ByAtLeast.new(1) { object.length }
      #
      # @param expected [#object_id]  An expected delta.
      # @param state    [Proc]        A block of code to execute to get the
      #   state of the object.
      def initialize(expected, &state)
        raise ::ArgumentError, "expected must be a Numeric" unless expected.is_a?(::Numeric)
        raise ::ArgumentError, "a block must be provided" unless block_given?
        raise ::ArgumentError, "expected must be non-negative" if expected.negative?

        @expected = expected
        @state    = state
      end

      # Boolean comparison on the expected change by comparing the value
      # before and after the code execution.
      #
      # @example
      #   require "matchi/change/by_at_least"
      #
      #   object = []
      #
      #   matcher = Matchi::Change::ByAtLeast.new(1) { object.length }
      #   matcher.match? { object << "foo" } # => true
      #
      # @yieldreturn [#object_id] The block of code to execute.
      #
      # @return [Boolean] Comparison between the value before and after the
      #   code execution.
      def match?
        raise ::ArgumentError, "a block must be provided" unless block_given?

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

        @expected <= (value_after - value_before)
      end

      # Returns a string representing the matcher.
      #
      # @return [String] a human-readable description of the matcher
      def to_s
        "change by at least #{@expected.inspect}"
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
matchi-4.1.1 lib/matchi/change/by_at_least.rb
matchi-4.1.0 lib/matchi/change/by_at_least.rb
matchi-4.0.0 lib/matchi/change/by_at_least.rb