Class: Minicrest::ContainsExactly

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

Overview

Matcher that checks if an array contains exactly the specified items in the specified order.

Examples:

contains_exactly(1, 2, 3).matches?([1, 2, 3])  # => true
contains_exactly(1, 2, 3).matches?([3, 1, 2])  # => false (wrong order)
contains_exactly(1, 2).matches?([1, 2, 3])     # => false (extra element)

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(*items) ⇒ ContainsExactly

Creates a new contains_exactly matcher.

Parameters:

  • items (Array)

    the items that must be contained in order



14
15
16
17
# File 'lib/minicrest/contains_exactly.rb', line 14

def initialize(*items)
  super()
  @items = items
end

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



30
31
32
# File 'lib/minicrest/contains_exactly.rb', line 30

def description
  "contains exactly #{@items.inspect} (in order)"
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Array)

    the array that was checked

Returns:

  • (String)

    failure message showing differences



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/minicrest/contains_exactly.rb', line 38

def failure_message(actual)
  actual_array = actual.to_a
  lines = ["expected #{actual.inspect} to contain exactly #{@items.inspect} (in order)"]

  if actual_array.length == @items.length
    @items.each_with_index do |expected_item, index|
      actual_item = actual_array[index]
      if expected_item != actual_item
        lines << "at index #{index}: expected #{expected_item.inspect}, got #{actual_item.inspect}"
      end
    end
  else
    lines << "expected size #{@items.length}, got #{actual_array.length}"
  end

  lines.join("\n")
end

#matches?(actual) ⇒ Boolean

Checks if actual contains exactly the expected items in order.

Parameters:

  • actual (Array)

    the array to check

Returns:

  • (Boolean)

    true if arrays are equal



23
24
25
# File 'lib/minicrest/contains_exactly.rb', line 23

def matches?(actual)
  actual.to_a == @items
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (Array)

    the array that was checked

Returns:

  • (String)

    message indicating unexpected match



60
61
62
63
64
# File 'lib/minicrest/contains_exactly.rb', line 60

def negated_failure_message(actual)
  <<~MSG.chomp
    expected #{actual.inspect} not to contain exactly #{@items.inspect} (in order), but it did
  MSG
end