From dabd3a7658330845f5c7eb6a125ed2b312006b7d Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Sun, 3 Nov 2019 13:59:38 -0700 Subject: [PATCH] Use ranges to specify call count --- src/spectator/matchers/receive_matcher.cr | 39 ++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/src/spectator/matchers/receive_matcher.cr b/src/spectator/matchers/receive_matcher.cr index 0915821..8d3a544 100644 --- a/src/spectator/matchers/receive_matcher.cr +++ b/src/spectator/matchers/receive_matcher.cr @@ -3,7 +3,9 @@ require "./standard_matcher" module Spectator::Matchers struct ReceiveMatcher < StandardMatcher - def initialize(@expected : TestExpression(Symbol), @count : Int32? = nil) + alias Range = ::Range(Int32, Int32) | ::Range(Nil, Int32) | ::Range(Int32, Nil) + + def initialize(@expected : TestExpression(Symbol), @range : Range? = nil) end def description : String @@ -13,8 +15,8 @@ module Spectator::Matchers def match?(actual : TestExpression(T)) : Bool forall T double = actual.value.as(Mocks::Double) calls = double.spectator_stub_calls(@expected.value) - if (count = @count) - count == calls.size + if (range = @range) + range.includes?(calls.size) else !calls.empty? end @@ -27,10 +29,39 @@ module Spectator::Matchers def values(actual : TestExpression(T)) forall T double = actual.value.as(Mocks::Double) calls = double.spectator_stub_calls(@expected.value) + range = @range { - expected: "#{@count ? "#{@count} time(s)" : "At least once"} with any arguments", + expected: "#{range ? "#{humanize_range(range)} time(s)" : "At least once"} with any arguments", received: "#{calls.size} time(s) with any arguments", } end + + def once + ReceiveMatcher.new(@expected, (1..1)) + end + + def twice + ReceiveMatcher.new(@expected, (2..2)) + end + + def humanize_range(range : Range) + if (min = range.begin) + if (max = range.end) + if min == max + min + else + "#{min} to #{max}" + end + else + "At least #{min}" + end + else + if (max = range.end) + "At most #{max}" + else + raise "Unexpected endless range" + end + end + end end end