From 0c4ffdf587ab49fd48d22b4070f445a505e98092 Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Fri, 1 Feb 2019 20:27:51 -0700 Subject: [PATCH] Allow `have` matcher to take multiple values --- src/spectator/dsl/matcher_dsl.cr | 11 +++++++++-- src/spectator/matchers/have_matcher.cr | 18 +++++++++++------- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/spectator/dsl/matcher_dsl.cr b/src/spectator/dsl/matcher_dsl.cr index 940d160..fe3f7e3 100644 --- a/src/spectator/dsl/matcher_dsl.cr +++ b/src/spectator/dsl/matcher_dsl.cr @@ -384,8 +384,15 @@ module Spectator::DSL # expect(%w[FOO BAR BAZ]).to have(/bar/i) # expect([1, 2, 3, :a, :b, :c]).to have(Int32) # ``` - macro have(expected) - ::Spectator::Matchers::HaveMatcher.new({{expected.stringify}}, {{expected}}) + # + # Additionally, multiple arguments can be specified. + # ``` + # expect("foobarbaz").to have("foo", "bar") + # expect(%i[a b c]).to have(:a, :b) + # expect(%w[FOO BAR BAZ]).to have(/foo/i, String) + # ``` + macro have(*expected) + ::Spectator::Matchers::HaveMatcher.new({{expected.splat.stringify}}, {{expected}}) end end end diff --git a/src/spectator/matchers/have_matcher.cr b/src/spectator/matchers/have_matcher.cr index 6e83149..8b3e314 100644 --- a/src/spectator/matchers/have_matcher.cr +++ b/src/spectator/matchers/have_matcher.cr @@ -1,7 +1,7 @@ require "./value_matcher" module Spectator::Matchers - # Matcher that tests whether a value, such as a `String` or `Array`, matches a value. + # Matcher that tests whether a value, such as a `String` or `Array`, matches one or more values. # For a `String`, the `includes?` method is used. # Otherwise, it expects an `Enumerable` and iterates over each item until `===` is true. struct HaveMatcher(ExpectedType) < ValueMatcher(ExpectedType) @@ -16,19 +16,23 @@ module Spectator::Matchers end end - # Checks if a `String` matches the expected value. + # Checks if a `String` matches the expected values. # The `includes?` method is used for this check. private def match_string?(actual) - actual.includes?(expected) + expected.all? do |item| + actual.includes?(item) + end end - # Checks if an `Enumerable` matches the expected value. + # Checks if an `Enumerable` matches the expected values. # The `===` operator is used on every item. private def match_enumerable?(actual) - actual.each do |item| - return true if expected === item + array = actual.to_a + expected.all? do |item| + array.any? do |elem| + item === elem + end end - false end # Describes the condition that satisfies the matcher.