|
require "spec_helper" |
|
require "active_model" |
|
|
|
require "json-schema" |
|
require_relative "../../../app/models/concerns/validators/json_validator" |
|
|
|
RSpec.describe Validators::JsonValidator do |
|
class Validatable |
|
include ActiveModel::Validations |
|
|
|
def initialize(attrs = {}) |
|
@data = attrs[:data].to_json |
|
end |
|
|
|
attr_accessor :data |
|
end |
|
|
|
describe "options" do |
|
it "accepts attribute, schema_root, and schema" do |
|
expect { |
|
Validators::JsonValidator.new( |
|
attribute: "data", schema_root: "/", schema: {} |
|
) |
|
}.not_to raise_error |
|
end |
|
|
|
context "without attribute" do |
|
it "raises an error" do |
|
expect { |
|
Validators::JsonValidator.new(schema_root: "/", schema: {}) |
|
}.to raise_error(KeyError) |
|
end |
|
end |
|
|
|
context "without schema" do |
|
it "raises an error" do |
|
expect { |
|
Validators::JsonValidator.new(attribute: "data", schema_root: "/") |
|
}.to raise_error(KeyError) |
|
end |
|
end |
|
|
|
context "without schema_root" do |
|
it "defaults to default_schema_root" do |
|
stub_const "Rails", double(root: "/") |
|
|
|
validator = Validators::JsonValidator.new(attribute: "data", schema: {}) |
|
|
|
expect(validator.schema_root) |
|
.to eq("/app/models/json_schemas") |
|
end |
|
end |
|
|
|
describe "schema" do |
|
context "as file" do |
|
it "loads the schema json from schema_root" do |
|
expect(File).to receive(:read).with("/schema_root/some_schema.json") |
|
.and_return('{ "type": "string" }') |
|
|
|
validator = Validators::JsonValidator.new(attribute: "data", |
|
schema_root: "/schema_root", |
|
schema: :some_schema) |
|
|
|
expect(validator.schema).to eq('{ "type": "string" }') |
|
end |
|
end |
|
|
|
context "not a file" do |
|
it "falls back to schema" do |
|
validator = Validators::JsonValidator.new( |
|
attribute: "data", |
|
schema_root: "/i/dont/exists", |
|
schema: { type: "object" } |
|
) |
|
|
|
expect(validator.schema).to eq({ type: "object" }) |
|
end |
|
end |
|
end |
|
end |
|
|
|
describe "#validate" do |
|
let(:validator) { |
|
Validators::JsonValidator.new(attribute: "data", |
|
schema_root: "/arbitrary/path", |
|
schema: { type: "object" }) |
|
} |
|
|
|
context "with valid data" do |
|
it "does not add an error to the field" do |
|
record = Validatable.new(data: {}) |
|
|
|
validator.validate(record) |
|
|
|
expect(record.errors[:data]).to be_empty |
|
end |
|
end |
|
|
|
context "with invalid data" do |
|
it "adds an error to the field" do |
|
record = Validatable.new(data: 'invalid') |
|
|
|
validator.validate(record) |
|
|
|
expect(record.errors[:data]).to include( |
|
I18n.t("errors.messages.invalid_json_schema") |
|
) |
|
end |
|
end |
|
end |
|
end |