Class: Minicrest::IsIn

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

Overview

Matcher that checks if a value is present in a collection.

Works with: - Arrays: checks if element is in array - Hashes: checks if key is in hash - Strings: checks if substring is in string - Ranges: checks if value is in range

Examples:

With arrays

is_in([1, 2, 3]).matches?(2)  # => true

With hashes (checks keys)

is_in({a: 1, b: 2}).matches?(:a)  # => true

With strings

is_in('hello').matches?('ell')  # => true

With ranges

is_in(1..10).matches?(5)  # => true

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(collection) ⇒ IsIn

Creates a new is_in matcher.

Parameters:

  • collection (Array, Hash, String, Range)

    the collection to check membership in



27
28
29
30
# File 'lib/minicrest/is_in.rb', line 27

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

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



47
48
49
# File 'lib/minicrest/is_in.rb', line 47

def description
  "in #{format_collection(@collection)}"
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



55
56
57
58
59
# File 'lib/minicrest/is_in.rb', line 55

def failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect} to be in #{format_collection(@collection)}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual is in the collection.

Parameters:

  • actual (Object)

    the value to check

Returns:

  • (Boolean)

    true if actual is in the collection



36
37
38
39
40
41
42
# File 'lib/minicrest/is_in.rb', line 36

def matches?(actual)
  if @collection.is_a?(Hash)
    @collection.key?(actual)
  else
    @collection.include?(actual)
  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)

    message indicating unexpected membership



65
66
67
68
69
# File 'lib/minicrest/is_in.rb', line 65

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect} not to be in #{format_collection(@collection)}, but it was
  MSG
end