Refactor collection matcher

This commit is contained in:
Michael Miller 2019-08-07 00:07:39 -06:00
parent ec96bf2de2
commit f2f46418a3

View file

@ -1,18 +1,24 @@
require "../test_value"
require "./range_matcher"
require "./value_matcher"
module Spectator::Matchers
# Matcher for checking that a value is in a collection of other values.
struct CollectionMatcher(ExpectedType) < ValueMatcher(ExpectedType)
# Determines whether the matcher is satisfied with the value given to it.
private def match?(actual)
expected.includes?(actual)
expected.value.includes?(actual.value)
end
# Determines whether the matcher is satisfied with the partial given to it.
def match(partial, negated = false)
actual = partial.actual
matched = match?(actual)
MatchData.new(matched, ExpectedActual.new(partial, self))
def description
"is in #{expected.label}"
end
private def failure_message(actual)
"#{actual.label} is not in #{expected.label}"
end
private def failure_message_when_negated(actual)
"#{actual.label} is in #{expected.label}"
end
# Creates a new range matcher with bounds based off of *center*.
@ -20,7 +26,7 @@ module Spectator::Matchers
# This method expects that the original matcher was created with a "difference" value.
# That is:
# ```
# RangeMatcher.new(diff).of(center)
# CollectionMatcher.new(diff).of(center)
# ```
# This implies that the `#match` method would not work on the original matcher.
#
@ -28,39 +34,12 @@ module Spectator::Matchers
# and have upper and lower bounds equal to *center* plus and minus diff.
# The range will be inclusive.
def of(center)
diff = @expected
diff = @expected.value
lower = center - diff
upper = center + diff
range = Range.new(lower, upper)
RangeMatcher.new(range, "#{center} +/- #{label}")
end
# Match data specific to this matcher.
private struct MatchData(ExpectedType, ActualType) < MatchData
# Creates the match data.
def initialize(matched, @values : ExpectedActual(ExpectedType, ActualType))
super(matched)
end
# Information about the match.
def named_tuple
{
collection: NegatableMatchDataValue.new(@values.expected),
actual: @values.actual,
}
end
# Describes the condition that satisfies the matcher.
# This is informational and displayed to the end-user.
def message
"#{@values.actual_label} is in #{@values.expected_label}"
end
# Describes the condition that won't satsify the matcher.
# This is informational and displayed to the end-user.
def negated_message
"#{@values.actual_label} is not in #{@values.expected_label}"
end
test_value = TestValue.new(range, "#{center} +/- #{expected.label}")
RangeMatcher.new(test_value)
end
end
end