From ae26377b3d18fe5c09c169260bbd34e75c800fa6 Mon Sep 17 00:00:00 2001 From: Michael Miller Date: Tue, 9 Feb 2021 19:10:11 -0700 Subject: [PATCH] Test and improve "Anything" --- spec/spectator/anything_spec.cr | 49 +++++++++++++++++++++++++++++++++ src/spectator/anything.cr | 21 ++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 spec/spectator/anything_spec.cr diff --git a/spec/spectator/anything_spec.cr b/spec/spectator/anything_spec.cr new file mode 100644 index 0000000..11672a5 --- /dev/null +++ b/spec/spectator/anything_spec.cr @@ -0,0 +1,49 @@ +require "../spec_helper" + +Spectator.describe Spectator::Anything do + it "equals everything" do + expect(true).to eq(subject) + expect(false).to eq(subject) + expect(nil).to eq(subject) + expect(42).to eq(subject) + expect(42.as(Int32 | String)).to eq(subject) + expect(["foo", "bar"]).to eq(subject) + end + + it "matches everything" do + expect(true).to match(subject) + expect(false).to match(subject) + expect(nil).to match(subject) + expect(42).to match(subject) + expect(42.as(Int32 | String)).to match(subject) + expect(["foo", "bar"]).to match(subject) + end + + context "nested in a container" do + it "equals everything" do + expect(["foo", "bar"]).to eq(["foo", subject]) + expect({"foo", "bar"}).to eq({"foo", subject}) + expect({foo: "bar"}).to eq({foo: subject}) + expect({"foo" => "bar"}).to eq({"foo" => subject}) + end + + it "matches everything" do + expect(["foo", "bar"]).to match(["foo", subject]) + expect({"foo", "bar"}).to match({"foo", subject}) + expect({foo: "bar"}).to match({foo: subject}) + expect({"foo" => "bar"}).to match({"foo" => subject}) + end + end + + describe "#to_s" do + subject { super.to_s } + + it { is_expected.to contain("anything") } + end + + describe "#inspect" do + subject { super.inspect } + + it { is_expected.to contain("anything") } + end +end diff --git a/src/spectator/anything.cr b/src/spectator/anything.cr index 511a024..6dafc60 100644 --- a/src/spectator/anything.cr +++ b/src/spectator/anything.cr @@ -1,15 +1,36 @@ module Spectator + # Type dedicated to matching everything. + # This is intended to be used as a value to compare against when the value doesn't matter. + # Can be used like so: + # ``` + # anything = Spectator::Anything.new + # array = ["foo", anything] + # expect(["foo", "bar"]).to eq(array) + # ``` struct Anything + # Always returns true. def ==(other) true end + # Always returns true. def ===(other) true end + # Always returns true. def =~(other) true end + + # Displays "anything". + def to_s(io) + io << "anything" + end + + # Displays "". + def inspect(io) + io << "" + end end end