From 93e270f87aa0e1df210d9c96c15a49c9cd8a0ec6 Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Sat, 17 Apr 2021 09:38:29 -0600 Subject: [PATCH] Support variables and methods for type matcher (be_a). Addresses https://github.com/icy-arctic-fox/spectator/issues/25 --- spec/matchers/type_matcher_spec.cr | 26 ++++++++++++++++++++++++++ src/spectator/dsl/matchers.cr | 2 +- src/spectator/matchers/type_matcher.cr | 5 +++++ 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 spec/matchers/type_matcher_spec.cr diff --git a/spec/matchers/type_matcher_spec.cr b/spec/matchers/type_matcher_spec.cr new file mode 100644 index 0000000..22d218e --- /dev/null +++ b/spec/matchers/type_matcher_spec.cr @@ -0,0 +1,26 @@ +require "../spec_helper" + +Spectator.describe Spectator::Matchers::TypeMatcher do + context String do # Sets `described_class` to String + def other_type + Int32 + end + + describe "#|" do + it "works on sets" do + super_set = (described_class | other_type) + + expect(42).to be_kind_of(super_set) + expect("foo").to be_a(super_set) + end + end + + it "works on described_class" do + expect("foo").to be_a_kind_of(described_class) + end + + it "works on plain types" do + expect(42).to be_a(Int32) + end + end +end diff --git a/src/spectator/dsl/matchers.cr b/src/spectator/dsl/matchers.cr index 9deb404..8332c44 100644 --- a/src/spectator/dsl/matchers.cr +++ b/src/spectator/dsl/matchers.cr @@ -77,7 +77,7 @@ module Spectator # expect(x).to be_a(Int32 | String) # ``` macro be_a(expected) - ::Spectator::Matchers::TypeMatcher({{expected}}).new + ::Spectator::Matchers::TypeMatcher.create({{expected}}) end # Indicates that some value should be of a specified type. diff --git a/src/spectator/matchers/type_matcher.cr b/src/spectator/matchers/type_matcher.cr index f8401d4..325265a 100644 --- a/src/spectator/matchers/type_matcher.cr +++ b/src/spectator/matchers/type_matcher.cr @@ -4,6 +4,11 @@ module Spectator::Matchers # Matcher that tests a value is of a specified type. # The values are compared with the `Object#is_a?` method. struct TypeMatcher(Expected) < StandardMatcher + # Alternate constructor that works with constant types and types from variables. + def self.create(type : T.class) forall T + TypeMatcher(T).new + end + # Short text about the matcher's purpose. # This explains what condition satisfies the matcher. # The description is used when the one-liner syntax is used.