Sha256: b3ac2e87a7388c955830d2b9c1519cc667c180b7fc5e94026d9fc0d6f3bdf3e6

Contents?: true

Size: 1.69 KB

Versions: 3

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

module Matchi
  class Change
    # *Change by* matcher.
    class By
      # Initialize the matcher with an object and a block.
      #
      # @example
      #   require "matchi/change/by"
      #
      #   object = []
      #
      #   Matchi::Change::By.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?

        @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"
      #
      #   object = []
      #
      #   matcher = Matchi::Change::By.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 #{@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.rb
matchi-4.1.0 lib/matchi/change/by.rb
matchi-4.0.0 lib/matchi/change/by.rb