Class: Matchi::Be

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

Overview

Identity matcher that checks if two objects are the exact same instance.

This matcher verifies object identity using Ruby’s Object#equal? method, which compares object IDs to determine if two references point to the exact same object in memory. This is different from equality comparison (==) which compares values.

Examples:

Basic usage with symbols

matcher = Matchi::Be.new(:foo)
matcher.match? { :foo }             # => true
matcher.match? { :bar }             # => false

Identity comparison with strings

string = "test"
matcher = Matchi::Be.new(string)
matcher.match? { string }           # => true
matcher.match? { string.dup }       # => false
matcher.match? { "test" }           # => false

With mutable objects

array = [1, 2, 3]
matcher = Matchi::Be.new(array)
matcher.match? { array }            # => true
matcher.match? { array.dup }        # => false
matcher.match? { [1, 2, 3] }        # => false

See Also:

Instance Method Summary collapse

Constructor Details

#initialize(expected) ⇒ Be

Initialize the matcher with a reference object.

Examples:

string = "test"
Be.new(string)             # Match only the same string instance

Parameters:

  • expected (#equal?)

    The expected identical object



43
44
45
# File 'lib/matchi/be.rb', line 43

def initialize(expected)
  @expected = expected
end

Instance Method Details

#match? { ... } ⇒ Boolean

Checks if the yielded object is the same instance as the expected object.

This method uses Ruby’s Object#equal? method, which performs identity comparison by comparing object IDs. Two objects are considered identical only if they are the exact same instance in memory.

Examples:

obj = "test"
matcher = Be.new(obj)
matcher.match? { obj }      # => true
matcher.match? { obj.dup }  # => false

Yields:

  • Block that returns the object to check

Yield Returns:

  • (Object)

    The object to verify identity with

Returns:

  • (Boolean)

    true if both objects are the same instance

Raises:

  • (ArgumentError)

    if no block is provided



67
68
69
70
71
# File 'lib/matchi/be.rb', line 67

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

  @expected.equal?(yield)
end

#to_sString

Returns a human-readable description of the matcher.

Examples:

Be.new("test").to_s # => 'be "test"'

Returns:

  • (String)

    A string describing what this matcher verifies



81
82
83
# File 'lib/matchi/be.rb', line 81

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