Add have_size matcher

This commit is contained in:
Michael Miller 2019-06-09 12:44:46 -06:00
parent bc4d0117a3
commit bb2b834662
3 changed files with 174 additions and 0 deletions

View file

@ -470,6 +470,16 @@ module Spectator::DSL
::Spectator::Matchers::ArrayMatcher.new({{expected}}, {{expected.stringify}})
end
# Indicates that some set should have a specified size.
#
# Example:
# ```
# expect([1, 2, 3]).to have_size(3)
# ```
macro have_size(expected)
::Spectator::Matchers::SizeMatcher.new({{expected}}, {{expected.stringify}})
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,43 @@
require "./value_matcher"
module Spectator::Matchers
# Matcher that tests whether a set has a specified number of elements.
# The set's `#size` method is used for this check.
struct SizeMatcher(ExpectedType) < ValueMatcher(ExpectedType)
# Determines whether the matcher is satisfied with the partial given to it.
# `MatchData` is returned that contains information about the match.
def match(partial)
actual = partial.actual.size
values = ExpectedActual.new(expected, label, actual, partial.label)
MatchData.new(actual == expected, values)
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
{
expected: 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} has #{@values.expected_label} elements"
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} does not have #{@values.expected_label} elements"
end
end
end
end