Class: Minicrest::AllItems

Inherits:
CollectionItemMatcher show all
Defined in:
lib/minicrest/all_items.rb

Overview

Matcher that checks if all items in a collection match a given matcher.

Examples:

Basic usage

all_items(descends_from(Integer)).matches?([1, 2, 3])  # => true
all_items(descends_from(Integer)).matches?([1, 'two', 3])  # => false

With comparison matchers

all_items(is_greater_than(0)).matches?([1, 2, 3])  # => true

See Also:

Instance Method Summary collapse

Methods inherited from CollectionItemMatcher

#collection?, #initialize

Methods inherited from Matcher

#&, #|

Constructor Details

This class inherits a constructor from Minicrest::CollectionItemMatcher

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



29
30
31
# File 'lib/minicrest/all_items.rb', line 29

def description
  "all items are #{@item_matcher.description}"
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Enumerable)

    the collection that was checked

Returns:

  • (String)

    failure message showing failing item



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/minicrest/all_items.rb', line 37

def failure_message(actual)
  return "expected a collection, but got #{actual.inspect}" unless collection?(actual)

  failing_index = actual.find_index { |item| !@item_matcher.matches?(item) }
  failing_item = actual.to_a[failing_index]
  item_failure = item_failure_message(failing_item)

  <<~MSG.chomp
    expected all items to be #{@item_matcher.description}
    item at index #{failing_index} failed:
    #{item_failure}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if all items match the item matcher.

Parameters:

  • actual (Enumerable)

    the collection to check

Returns:

  • (Boolean)

    true if all items match



20
21
22
23
24
# File 'lib/minicrest/all_items.rb', line 20

def matches?(actual)
  return false unless collection?(actual)

  actual.all? { |item| @item_matcher.matches?(item) }
end

#negated_failure_message(_actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • _actual (Enumerable)

    the collection that was checked

Returns:

  • (String)

    message indicating unexpected match



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

def negated_failure_message(_actual)
  <<~MSG.chomp
    expected not all items to be #{@item_matcher.description}, but they all matched
  MSG
end