Class: Minicrest::HasKey

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

Overview

Matcher that checks if a hash contains specified keys.

Examples:

Single key

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

Multiple keys

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

Instance Method Summary collapse

Methods inherited from Matcher

#&, #|

Constructor Details

#initialize(*keys) ⇒ HasKey

Creates a new has_key matcher.

Parameters:

  • keys (Array<Symbol, String>)

    the keys that must be present



15
16
17
18
# File 'lib/minicrest/has_key.rb', line 15

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

Instance Method Details

#descriptionString

Returns a description of what this matcher expects.

Returns:

  • (String)

    description



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

def description
  if @keys.length == 1
    "has key #{@keys.first.inspect}"
  else
    "has keys #{@keys.map(&:inspect).join(', ')}"
  end
end

#failure_message(actual) ⇒ String

Returns the failure message when the match fails.

Parameters:

  • actual (Hash)

    the hash that was checked

Returns:

  • (String)

    failure message listing missing keys



47
48
49
50
51
52
53
54
55
# File 'lib/minicrest/has_key.rb', line 47

def failure_message(actual)
  return "expected a Hash, but got #{actual.inspect}" unless actual.respond_to?(:key?)

  missing = @keys.reject { |key| actual.key?(key) }
  <<~MSG.chomp
    expected #{format_hash(actual)} to have keys #{@keys.map(&:inspect).join(', ')}
    missing: #{missing.map(&:inspect).join(', ')}
  MSG
end

#matches?(actual) ⇒ Boolean

Checks if actual hash contains all expected keys.

Parameters:

  • actual (Hash)

    the hash to check

Returns:

  • (Boolean)

    true if all keys are present



24
25
26
27
28
29
30
# File 'lib/minicrest/has_key.rb', line 24

def matches?(actual)
  return false unless actual.respond_to?(:key?)

  @keys.all? { |key| actual.key?(key) }
rescue NoMethodError
  false
end

#negated_failure_message(actual) ⇒ String

Returns the failure message when a negated match fails.

Parameters:

  • actual (Hash)

    the hash that was checked

Returns:

  • (String)

    message indicating unexpected key presence



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/minicrest/has_key.rb', line 61

def negated_failure_message(actual)
  if @keys.length == 1
    <<~MSG.chomp
      expected #{format_hash(actual)} not to have key #{@keys.first.inspect}, but it did
    MSG
  else
    <<~MSG.chomp
      expected #{format_hash(actual)} not to have keys #{@keys.map(&:inspect).join(', ')}, but it did
    MSG
  end
end