Class: Minicrest::Is

Inherits:
Matcher show all
Defined in:
lib/minicrest/is.rb

Overview

Matcher that checks for reference equality (same object identity).

Uses Ruby’s equal? method which checks if two references point to the exact same object in memory.

Examples:

Basic usage

obj = Object.new
same_ref = obj
different_obj = Object.new

is(obj).matches?(same_ref)      # => true
is(obj).matches?(different_obj) # => false

With strings (reference vs value)

str = "hello"
is(str).matches?(str)       # => true (same reference)
is(str).matches?("hello")   # => false (different object, same value)

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(expected) ⇒ Is

Creates a new reference equality matcher.

Parameters:

  • expected (Object, Matcher)

    the expected object reference or a matcher



25
26
27
28
# File 'lib/minicrest/is.rb', line 25

def initialize(expected)
  super()
  @expected = expected
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



45
46
47
48
49
50
51
# File 'lib/minicrest/is.rb', line 45

def description
  if @expected.is_a?(Matcher)
    @expected.description
  else
    "the same object as #{@expected.inspect} (object_id: #{@expected.object_id})"
  end
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Object)

    the value that was checked

Returns:

  • (String)

    failure message



57
58
59
60
61
62
63
64
65
# File 'lib/minicrest/is.rb', line 57

def failure_message(actual)
  if @expected.is_a?(Matcher)
    @expected.failure_message(actual)
  else
    <<~MSG.chomp
      expected #{actual.inspect} (object_id: #{actual.object_id}) to be the same object as #{@expected.inspect} (object_id: #{@expected.object_id})
    MSG
  end
end

#matches?(actual) ⇒ Boolean

Checks if actual is the same object as expected, or matches if expected is a matcher.

Parameters:

  • actual (Object)

    the value to check

Returns:

  • (Boolean)

    true if actual matches



34
35
36
37
38
39
40
# File 'lib/minicrest/is.rb', line 34

def matches?(actual)
  if @expected.is_a?(Matcher)
    @expected.matches?(actual)
  else
    actual.equal?(@expected)
  end
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (Object)

    the value that was checked

Returns:

  • (String)

    failure message



71
72
73
74
75
76
77
78
79
# File 'lib/minicrest/is.rb', line 71

def negated_failure_message(actual)
  if @expected.is_a?(Matcher)
    @expected.negated_failure_message(actual)
  else
    <<~MSG.chomp
      expected #{actual.inspect} (object_id: #{actual.object_id}) not to be the same object as #{@expected.inspect}, but they are the same object
    MSG
  end
end