Sha256: 8c286233b8700c9440dff1c967a90815f2989d5dee2b86ba07a65c3015e43d06

Contents?: true

Size: 1.57 KB

Versions: 1

Compression:

Stored size: 1.57 KB

Contents

require "dry-matcher"
require "dry-monads"

RSpec.describe "Custom matcher" do
  let(:transaction) {
    Dry.Transaction(container: container, matcher: Test::CustomMatcher) do
      step :process
      step :validate, failure: :bad_value
      step :persist
    end
  }

  let(:container) {
    {
      process: -> input { Dry::Monads.Right(name: input["name"], email: input["email"]) },
      validate: -> input { input[:email].nil? ? Dry::Monads.Left(:email_required) : Dry::Monads.Right(input) },
      persist:  -> input { Test::DB << input and Dry::Monads.Right(input) }
    }
  }

  before do
    Test::DB = []
    Test::QUEUE = []

    module Test
      CustomMatcher = Dry::Matcher.new(
        yep: Dry::Matcher::Case.new(
          match: -> result { result.right? },
          resolve: -> result { result.value }
        ),
        nup: Dry::Matcher::Case.new(
          match: -> result, failure = nil {
            if failure
              result.left? && result.value.step.options[:failure] == failure
            else
              result.left?
            end
          },
          resolve: -> result { result.value.value }
        )
      )
    end
  end

  it "supports a custom matcher" do
    matches = -> m {
      m.yep { |v| "Yep! #{v[:email]}" }
      m.nup(:bad_value) { |v| "Nup. #{v.to_s}" }
    }

    input = {"name" => "Jane", "email" => "jane@doe.com"}
    result = transaction.(input, &matches)
    expect(result).to eq "Yep! jane@doe.com"

    input = {"name" => "Jane"}
    result = transaction.(input, &matches)
    expect(result).to eq "Nup. email_required"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dry-transaction-0.9.0 spec/integration/custom_matcher_spec.rb