Class: Minicrest::RespondsTo

Inherits:
Matcher
  • Object
show all
Defined in:
lib/minicrest/responds_to.rb

Overview

Matcher that checks if a value responds to specified methods.

Uses Ruby’s respond_to? method to check method availability.

Examples:

Single method

responds_to(:upcase).matches?("hello")  # => true

Multiple methods

responds_to(:push, :pop).matches?([])   # => true

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(*methods) ⇒ RespondsTo

Creates a new responds_to matcher.

Parameters:

  • methods (Array<Symbol>)

    the methods to check for



17
18
19
20
# File 'lib/minicrest/responds_to.rb', line 17

def initialize(*methods)
  super()
  @methods = methods.flatten
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description of expected methods



33
34
35
# File 'lib/minicrest/responds_to.rb', line 33

def description
  "respond to #{@methods.map(&:inspect).join(', ')}"
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Object)

    the value that was checked

Returns:

  • (String)

    message showing missing methods



41
42
43
44
45
46
47
48
# File 'lib/minicrest/responds_to.rb', line 41

def failure_message(actual)
  missing = @methods.reject { |method| actual.respond_to?(method) }
  <<~MSG.chomp
    expected #{actual.inspect}
          to respond to #{@methods.map(&:inspect).join(', ')}
    missing: #{missing.map(&:inspect).join(', ')}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual responds to all specified methods.

Parameters:

  • actual (Object)

    the value to check

Returns:

  • (Boolean)

    true if actual responds to all methods



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

def matches?(actual)
  @methods.all? { |method| actual.respond_to?(method) }
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)

    message indicating unexpected method availability



54
55
56
57
58
59
60
# File 'lib/minicrest/responds_to.rb', line 54

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect}
          not to respond to #{@methods.map(&:inspect).join(', ')}
    but it does
  MSG
end