Method: Spectus.may

Defined in:
lib/spectus.rb

.may(matcher) ⇒ Requirement::Optional

Defines an optional feature or behavior. This represents the RFC 2119 “MAY” level - where an item is truly optional. Implementations can freely choose whether to include the item based on their specific needs, while maintaining interoperability with other implementations.

For MAY requirements, a test passes in two cases:

  1. When a NoMethodError is raised, indicating the feature is not implemented

  2. When the feature is implemented and the test succeeds

Examples:

With a custom matcher testing an optional method

class RespondsTo
  def initialize(method)
    @method = method
  end

  def match?
    (yield).respond_to?(@method)
  end
end

test = Spectus.may RespondsTo.new(:to_h)
test.call { {} }                  # => pass (feature is implemented)
test.call { BasicObject.new }     # => pass (NoMethodError - feature not implemented)

With Matchi gem

require "spectus"
require "matchi/predicate"

test = Spectus.may Matchi::Predicate.new(:be_frozen)
test.call { "".freeze }           # => pass (feature is implemented)
test.call { BasicObject.new }     # => pass (NoMethodError - feature not implemented)

Parameters:

  • matcher (#match?)

    Any object that implements the matcher protocol

Returns:

Raises:

  • (ArgumentError)

    If matcher doesn’t respond to match?



203
204
205
206
207
# File 'lib/spectus.rb', line 203

def self.may(matcher)
  raise ::ArgumentError, "matcher must respond to match?" unless matcher.respond_to?(:match?)

  Requirement::Optional.new(negate: false, matcher:)
end