diff --git a/lib/json_matchers/matcher.rb b/lib/json_matchers/matcher.rb index 25cc592..914722c 100644 --- a/lib/json_matchers/matcher.rb +++ b/lib/json_matchers/matcher.rb @@ -19,6 +19,24 @@ def validation_failure_message errors.first.to_s end + class << self + attr_writer :document_store + + def document_store + @document_store ||= begin + document_store = JsonSchema::DocumentStore.new + + Dir.glob("#{JsonMatchers.schema_root}/**/*.json"). + map { |path| Pathname.new(path) }. + map { |schema_path| Parser.new(schema_path).parse }. + map { |schema| document_store.add_schema(schema) }. + each { |schema| schema.expand_references!(store: document_store) } + + document_store + end + end + end + private attr_accessor :errors @@ -29,15 +47,7 @@ def validator end def build_and_populate_document_store - document_store = JsonSchema::DocumentStore.new - - Dir.glob("#{JsonMatchers.schema_root}/**/*.json"). - map { |path| Pathname.new(path) }. - map { |schema_path| Parser.new(schema_path).parse }. - map { |schema| document_store.add_schema(schema) }. - each { |schema| schema.expand_references!(store: document_store) } - - document_store + self.class.document_store end end end diff --git a/spec/json_matchers/match_json_schema_spec.rb b/spec/json_matchers/match_json_schema_spec.rb index b48b01b..8f6e25f 100644 --- a/spec/json_matchers/match_json_schema_spec.rb +++ b/spec/json_matchers/match_json_schema_spec.rb @@ -59,6 +59,17 @@ expect(json).to match_json_schema("api/v1/schema") end + it "does not reload document store" do + create(:schema, :location, name: "api/v1/schema") + + json = build(:response, :location) + + expect(Dir).to receive(:glob).once.and_call_original + 2.times do + expect(json).to match_json_schema("api/v1/schema") + end + end + it "supports invalidating the referenced schema when using local references" do create(:schema, name: "post", json: { "$schema": "https://json-schema.org/draft-04/schema#", diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index c91de70..7f8c70f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -15,6 +15,7 @@ config.around do |example| ensure_fixtures("spec", "fixtures", "schemas") do + JsonMatchers::Matcher.document_store = nil example.run end end diff --git a/test/support/json_matchers/test_case.rb b/test/support/json_matchers/test_case.rb index 4ccecef..a9e511f 100644 --- a/test/support/json_matchers/test_case.rb +++ b/test/support/json_matchers/test_case.rb @@ -9,6 +9,7 @@ class TestCase < ::Minitest::Test def setup @original_schema_root = setup_fixtures("test", "fixtures", "schemas") + JsonMatchers::Matcher.document_store = nil end def teardown