Add have_key matcher

This commit is contained in:
Michael Miller 2019-02-05 12:47:50 -07:00
parent 8a09ddac04
commit c6b4e22666
3 changed files with 43 additions and 1 deletions

View file

@ -395,6 +395,23 @@ module Spectator::DSL
::Spectator::Matchers::HaveMatcher.new({{expected.splat.stringify}}, {{expected}})
end
# Indicates that some set, such as a `Hash`, has a given key.
# The `has_key?` method is used for this check.
#
# Examples:
# ```
# expect({foo: "bar"}).to have_key(:foo)
# expect({"lucky" => 7}).to have_key("lucky")
# ```
macro have_key(expected)
::Spectator::Matchers::HasKeyMatcher.new({{expected.stringify}}, {{expected}})
end
# ditto
macro has_key(expected)
have_key({{expected}})
end
# Indicates that some value should have a set of attributes matching some conditions.
# A list of named arguments are expected.
# The names correspond to the attributes in the instance to check.

View file

@ -0,0 +1,25 @@
require "./value_matcher"
module Spectator::Matchers
# Matcher that tests whether a `Hash` (or similar type) has a given key.
# The set is checked with the `has_key?` method.
struct HaveKeyMatcher(ExpectedType) < ValueMatcher(ExpectedType)
# Determines whether the matcher is satisfied with the value given to it.
# True is returned if the match was successful, false otherwise.
def match?(partial)
partial.actual.has_key?(expected)
end
# Describes the condition that satisfies the matcher.
# This is informational and displayed to the end-user.
def message(partial)
"Expected #{partial.label} to have key #{label}"
end
# Describes the condition that won't satsify the matcher.
# This is informational and displayed to the end-user.
def negated_message(partial)
"Expected #{partial.label} to not have key #{label}"
end
end
end