Tired of json-schema, try dry-validation

Validating JSON schemas with rspec + dry-validation

Photo by Siavash Ghanbari on Unsplash

Why you should use dry-validation over json-schema?


{
"type": "object",
"required": ["user"],
"properties": {
"user" : {
"type" : "object",
"required" : [
"id",
"token",
"token_expired_at",
"email",
"firstname",
"lastname",
"gender",
"phone_number",
"birthday"
],
"properties" : {
"id" : { "type" : "integer" },
"token" : { "type" : "string" },
"token_expired_at" : { "type" : "string" },
"email" : { "type" : "string" },
"lastname" : { "type" : "string" },
"firstname" : { "type" : "string" },
"gender" : { "type" : "string" },
"phone_number" : { "type" : "string" },
"brithday" : { "type" : "string", "format": "date-time" },
"updated_at" : { "type" : "string", "format": "date-time" },
"created_at" : { "type" : "string", "format": "date-time" },
}
}
}
}
describe "Sign in" do
context "anonymous user" do
it "returns data in the specified format" do
sign_in_as_anonymous
expect(response).tomatch_response_schema("users/anonymous_detail")
end
end
en

Creating the custom matcher

group :test do
gem "dry-validation"
end
RSpec::Matchers.define :match_schema do |schema|
match do |response|
@result = schema.call(JSON.parse(response.body, symbolize_names: true))
@result.success?
end
def failure_message
@result.errors
end
end

Defining the anonymous user schema

require "support/views/schemas"
AnonymousUserSchema = Dry::Validation.Schema do
required(:user).schema do
required(:email)
required(:token).filled
required(:token_expired_at).filled
required(:firstname)
required(:lastname)
required(:gender)
required(:phone_number)
required(:birthday)
end
end
describe "Sign in" do
context "anonymous user" do
it "returns data in the specified format" do
sign_in_as_anonymous

expect(response).to match_schema(AnonymousUserSchema)
end
end
end
AnonymousUserSchema = Dry::Validation.Schema do
required(:user).schema do
required(:email)
required(:token).filled
required(:token_expired_at).filled
required(:firstname)
required(:lastname)
required(:gender)
required(:phone_number)
required(:birthday)
required(:age).maybe(int?)
end
end

∞ Travel | Coding | Lifestyle ⦿ Bangkok | ✧ #freelancer ▷ Got a project? ⭣ www.upwork.com/fl/al3rez