Class: Matchi::Predicate

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

Overview

Predicate matcher: passes when a predicate method of the actual value returns true. The matcher name be_xxx calls xxx?, and have_xxx calls has_xxx?, with Kernel#public_send bound to the actual value. The predicate must return true or false; any other value is an error, not a truthy pass.

Since the actual value answers the call, this matcher depends on the honesty of the object under test. Use it for the object's own documented predicates.

Examples:

Matchi::Predicate.new(:be_empty).match? { [] }           # => true
Matchi::Predicate.new(:have_key, :a).match? { { a: 1 } } # => true

Constant Summary collapse

NAME =

A matcher name: be_ or have_, then a letter, then letters, digits or underscores, in any script. It never ends with ? or !.

/\A(be|have)_\p{Alpha}[\p{Alnum}_]*\z/

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Predicate.

Parameters:

  • name (Symbol, String) —

    be_xxx or have_xxx

  • args (Array) —

    positional arguments for the predicate

  • kwargs (Hash) —

    keyword arguments for the predicate

  • block (Proc, nil) —

    a block for the predicate

Raises:

  • (ArgumentError) —

    when the name does not start with be_ or have_



29
30
31
32
33
34
35
36
37
# File 'lib/matchi/predicate.rb', line 29

def initialize(name, *args, **kwargs, &block)
  @name = String(name)
  raise ::ArgumentError, "name must match #{NAME.inspect} (got: #{name.inspect})" unless NAME.match?(@name)

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

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    the actual value

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given

  • (TypeError) —

    when the predicate returns something other than true or false

  • (NoMethodError) —

    when the actual value has no such public predicate



44
45
46
47
48
49
50
51
# File 'lib/matchi/predicate.rb', line 44

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

  result = ::Kernel.instance_method(:public_send).bind_call(yield, @method_name, *@args, **@kwargs, &@block)
  return result if true.equal?(result) || false.equal?(result)

  raise ::TypeError, "#{@method_name} must return true or false (got a #{Constant.label(result_class(result))})"
end

#to_s ⇒ String

Returns:

  • (String)


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

def to_s
  arguments = @args.map(&:inspect) + @kwargs.map { |key, value| "#{key}: #{value.inspect}" }
  arguments << "&block" if @block

  [@name.tr("_", " "), arguments.join(", ")].reject(&:empty?).join(" ")
end