Class: Matchi::Predicate

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

Overview

Predicate matcher.

Instance Method Summary collapse

Constructor Details

#initialize(name, *args, **kwargs, &block) ⇒ Predicate

Initialize the matcher with a name and arguments.

Examples:

require "matchi/predicate"

Matchi::Predicate.new(:be_empty)

Parameters:

  • name (#to_s)

    A matcher name.

  • args (Array)

    A list of parameters.

  • kwargs (Hash)

    A list of keyword parameters.

  • block (Proc)

    A block of code.

Raises:

  • (::ArgumentError)

17
18
19
20
21
22
23
24
25
# File 'lib/matchi/predicate.rb', line 17

def initialize(name, *args, **kwargs, &block)
  @name = String(name)

  raise ::ArgumentError unless valid_name?

  @args   = args
  @kwargs = kwargs
  @block  = block
end

Instance Method Details

#expectedArray

Returns The method name with any arguments to send to the subject.

Returns:

  • (Array)

    The method name with any arguments to send to the subject.


28
29
30
# File 'lib/matchi/predicate.rb', line 28

def expected
  [method_name, @args, @kwargs, @block]
end

#inspectObject

A string containing a human-readable representation of the matcher.


61
62
63
# File 'lib/matchi/predicate.rb', line 61

def inspect
  "#{self.class}(#{@name}, *#{@args.inspect}, **#{@kwargs.inspect}, &#{@block.inspect})"
end

#matches?Boolean

Boolean comparison between the actual value and the expected value.

Examples:

require "matchi/predicate"

matcher = Matchi::Predicate.new(:be_empty)

matcher.expected        # => [:empty?, [], {}, nil]
matcher.matches? { [] } # => true
require "matchi/predicate"

matcher = Matchi::Predicate.new(:have_key, :foo)

matcher.expected                 # => [:has_key?, [:foo], {}, nil]
matcher.matches? { { foo: 42 } } # => true

Yield Returns:

  • (#object_id)

    The actual value to receive the method request.

Returns:

  • (Boolean)

    A boolean returned by the actual value being tested.

Raises:

  • (::TypeError)

53
54
55
56
57
58
# File 'lib/matchi/predicate.rb', line 53

def matches?
  value = yield.send(method_name, *@args, **@kwargs, &@block)
  return value if [false, true].include?(value)

  raise ::TypeError, "Boolean expected, but #{value.class} instance returned."
end

#to_sObject

Returns a string representing the matcher.


66
67
68
69
70
71
72
73
74
# File 'lib/matchi/predicate.rb', line 66

def to_s
  (
    "#{@name.tr('_', ' ')} " + [
      @args.map(&:inspect).join(", "),
      @kwargs.map { |k, v| "#{k}: #{v.inspect}" }.join(", "),
      (@block.nil? ? "" : "&block")
    ].reject { |i| i.eql?("") }.join(", ")
  ).strip
end