Sha256: 3d58ff5947512f1c72f482f57fba91d0a38764908c8dfda3d16a87ffe46d6827

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

require "dry-monads"

RSpec.describe Dry::Matcher do
  context "with match cases provided" do
    let(:success_case) {
      Dry::Matcher::Case.new(
        match: -> result { result.right? },
        resolve: -> result { result.value },
      )
    }

    let(:failure_case) {
      Dry::Matcher::Case.new(
        match: -> result { result.left? },
        resolve: -> result { result.value },
      )
    }

    let(:matcher) {
      Dry::Matcher.new(
        success: success_case,
        failure: failure_case,
      )
    }

    def call_match(input)
      matcher.(input) do |m|
        m.success do |v|
          "Success: #{v}"
        end

        m.failure do |v|
          "Failure: #{v}"
        end
      end
    end

    it "matches on success" do
      input = Dry::Monads::Right("Yes!")
      expect(call_match(input)).to eq "Success: Yes!"
    end

    it "matches on failure" do
      input = Dry::Monads::Left("No!")
      expect(call_match(input)).to eq "Failure: No!"
    end

    context "with patterns" do
      let(:failure_case) {
        Dry::Matcher::Case.new(
          match: -> result, failure_type {
            result.length == 3 && result[0] == :failure && result[1] == failure_type
          },
          resolve: -> result { result.last },
        )
      }

      def call_match(input)
        matcher.(input) do |m|
          m.failure :my_error do |v|
            "Pattern-matched failure: #{v}"
          end
        end
      end

      it "matches using the provided pattern" do
        input = [:failure, :my_error, "No!"]
        expect(call_match(input)).to eq "Pattern-matched failure: No!"
      end

      it "doesn't match if the pattern doesn't match" do
        input = [:failure, :non_matching_error, "No!"]
        expect(call_match(input)).to be_nil
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-matcher-0.5.0 spec/integration/matcher_spec.rb