From f9e31715e5ec94db87c5af8d11d2fa5e3b855a20 Mon Sep 17 00:00:00 2001 From: davidgisbey Date: Fri, 22 Jul 2022 11:26:32 +0100 Subject: [PATCH] Ensure the validator can handle the payload being JSON At the moment, there's some disparity between how applications that user Minitest and applications that use RSpec pass their payloads. RSpec applications pass the payload as JSON and Minitest applications pass it as a Hash. Currently, the payload is being converted to JSON before being validated by `JSON.fully_validate`. If the object is already JSON then .to_json is called again. This means when JSON.parse is called on the object it does not convert it back to a hash. This commit updates the validator to ensure that the payload is converted to JSON if the object passed is not a string. --- lib/govuk_schemas/validator.rb | 17 +++++++++++------ spec/lib/validator_spec.rb | 7 +++++++ 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/govuk_schemas/validator.rb b/lib/govuk_schemas/validator.rb index 01f5fbd..e75c242 100644 --- a/lib/govuk_schemas/validator.rb +++ b/lib/govuk_schemas/validator.rb @@ -1,11 +1,12 @@ module GovukSchemas class Validator - attr_reader :schema_name, :type, :payload + attr_reader :schema_name, :type + attr_accessor :payload def initialize(schema_name, type, payload) @schema_name = schema_name @type = type - @payload = payload + @payload = ensure_json(payload) end def valid? @@ -27,14 +28,12 @@ def error_message def errors schema = Schema.find("#{type}_schema": schema_name) - validator = JSON::Validator.fully_validate(schema, payload.to_json) + validator = JSON::Validator.fully_validate(schema, payload) validator.map { |message| "- " + humanized_error(message) }.join("\n") end def formatted_payload - return payload if payload.is_a?(String) - - JSON.pretty_generate(payload) + JSON.pretty_generate(JSON.parse(payload)) end def humanized_error(message) @@ -42,5 +41,11 @@ def humanized_error(message) .gsub(/in schema [0-9a-f\-]+/, "") .strip end + + def ensure_json(payload) + return payload if payload.is_a?(String) + + payload.to_json + end end end diff --git a/spec/lib/validator_spec.rb b/spec/lib/validator_spec.rb index 88ca00b..212f4f0 100644 --- a/spec/lib/validator_spec.rb +++ b/spec/lib/validator_spec.rb @@ -16,6 +16,13 @@ expect(validator.valid?).to eq false end + + it "handles the payload being passed as json" do + example = GovukSchemas::RandomExample.for_schema(publisher_schema: "placeholder").to_json + validator = described_class.new("placeholder", "publisher", example) + + expect(validator.valid?).to eq true + end end describe "#error_message" do