Class: Matchi::Eq

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

Overview

Equivalence matcher: passes when the actual value is of the same class as the expected value and eql? to it.

The expected value receives the eql? call, so the actual value cannot lie. The class check comes first because a few core eql? methods, such as Hash#eql?, hand the comparison back to an operand of another class; it costs nothing, since eql? never holds across classes for core values.

Examples:

Matchi::Eq.new("foo").match? { "foo" } # => true
Matchi::Eq.new(1).match? { 1.0 }       # => false (eql? is strict on type)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ Eq

Returns a new instance of Eq.

Parameters:

  • expected (#eql?) —

    the expected value



17
18
19
# File 'lib/matchi/eq.rb', line 17

def initialize(expected)
  @expected = expected
end

Class Method Details

.eql?(expected, actual) ⇒ Boolean

Returns whether actual is of the class of expected and eql? to it.

Parameters:

  • expected (#eql?) —

    the value that receives the comparison

  • actual (Object) —

    a value from the code under test

Returns:

  • (Boolean) —

    whether actual is of the class of expected and eql? to it



38
39
40
41
42
# File 'lib/matchi/eq.rb', line 38

def self.eql?(expected, actual)
  return false unless ::Kernel.instance_method(:class).bind_call(actual).equal?(expected.class)

  expected.eql?(actual) ? true : false
end

Instance Method Details

#match? ⇒ Boolean

Yield Returns:

  • (Object) —

    the actual value

Returns:

  • (Boolean)

Raises:

  • (ArgumentError) —

    when no block is given



24
25
26
27
28
# File 'lib/matchi/eq.rb', line 24

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

  Eq.eql?(@expected, yield)
end

#to_s ⇒ String

Returns:

  • (String)


31
32
33
# File 'lib/matchi/eq.rb', line 31

def to_s
  "eq #{@expected.inspect}"
end