Class: Minicrest::HasKey
Overview
Matcher that checks if a hash contains specified keys.
Instance Method Summary collapse
-
#description ⇒ String
Returns a description of what this matcher expects.
-
#failure_message(actual) ⇒ String
Returns the failure message when the match fails.
-
#initialize(*keys) ⇒ HasKey
constructor
Creates a new has_key matcher.
-
#matches?(actual) ⇒ Boolean
Checks if actual hash contains all expected keys.
-
#negated_failure_message(actual) ⇒ String
Returns the failure message when a negated match fails.
Methods inherited from Matcher
Constructor Details
#initialize(*keys) ⇒ HasKey
Creates a new has_key matcher.
15 16 17 18 |
# File 'lib/minicrest/has_key.rb', line 15 def initialize(*keys) super() @keys = keys end |
Instance Method Details
#description ⇒ String
Returns a description of what this matcher expects.
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.
47 48 49 50 51 52 53 54 55 |
# File 'lib/minicrest/has_key.rb', line 47 def (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.
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.
61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/minicrest/has_key.rb', line 61 def (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 |