Class: Minicrest::DescendsFrom

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

Overview

Matcher that checks if a value is an instance of a given type.

Uses Ruby’s is_a? method which checks class hierarchy and module inclusion.

Examples:

Basic usage

descends_from(String).matches?("hello")  # => true
descends_from(Integer).matches?(42)      # => true
descends_from(Enumerable).matches?([])   # => true (module inclusion)

With inheritance

descends_from(Exception).matches?(StandardError.new)  # => true (subclass)

See Also:

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(expected_type) ⇒ DescendsFrom

Creates a new type matcher.

Parameters:

  • expected_type (Class, Module)

    the expected type



103
104
105
106
# File 'lib/minicrest/value_matchers.rb', line 103

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

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description of expected type



119
120
121
# File 'lib/minicrest/value_matchers.rb', line 119

def description
  "an instance of #{@expected_type}"
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 expected vs actual type



127
128
129
130
131
132
133
# File 'lib/minicrest/value_matchers.rb', line 127

def failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect}
          to be an instance of #{@expected_type}
    but was #{actual.class}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual is an instance of the expected type.

Parameters:

  • actual (Object)

    the value to check

Returns:

  • (Boolean)

    true if actual.is_a?(expected_type)



112
113
114
# File 'lib/minicrest/value_matchers.rb', line 112

def matches?(actual)
  actual.is_a?(@expected_type)
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 type match



139
140
141
142
143
144
145
# File 'lib/minicrest/value_matchers.rb', line 139

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect}
          not to be an instance of #{@expected_type}
    but it is
  MSG
end