I’m trying to define a custom type to be used in multiple schemas but can’t get the validations to work. When I define the rules directly, errors are produced as expected. When I define a custom type, the rules provided in the type do not produce errors. What am I’m doing wrong here? Any help would be greatly appreciated.
module Types
include Dry::Types()
SSN = Types::Strict::String.constrained(size: 9, format: /\d{9}/)
end
module Schemas
SsnSearch = Dry::Schema.Params do
# vvv THIS WORKS vvv
# required(:ssn).filled(:string, size?: 9, format?: /\d{9}/)
# vvv THIS FAILS on "must be 9 characters" and "must be only numeric" vvv
required(:ssn).filled(Types::SSN)
end
end
RSpec.describe Schemas::SsnSearch do
specify "ssn is required" do
schema = described_class.call({})
expect(schema.errors.fetch(:ssn)).to include(/missing/)
end
specify "ssn is required" do
schema = described_class.call(ssn: nil)
expect(schema.errors.fetch(:ssn)).to include(/must be filled/)
end
specify "ssn must be a string" do
schema = described_class.call(ssn: 123456789)
expect(schema.errors.fetch(:ssn)).to include(/must be a string/)
end
specify "ssn must be 9 characters" do
schema = described_class.call(ssn: "1" * 8)
expect(schema.errors.fetch(:ssn)).to include(/must be 9/)
end
specify "ssn must be only numeric characters" do
schema = described_class.call(ssn: "12E4S6789")
expect(schema.errors.fetch(:ssn)).to include(/format/)
end
end