diff --git a/lib/openapi_first/schema/validation_error.rb b/lib/openapi_first/schema/validation_error.rb index c33a27c7..a1bf90de 100644 --- a/lib/openapi_first/schema/validation_error.rb +++ b/lib/openapi_first/schema/validation_error.rb @@ -6,7 +6,7 @@ module Schema ValidationError = Data.define(:value, :data_pointer, :schema_pointer, :type, :details, :schema) do # This returns an error message for this specific error. # This it copied from json_schemer here to be easier to customize when passing custom data_pointers. - def message + def message # rubocop:disable Metrics/CyclomaticComplexity location = data_pointer.empty? ? 'root' : "`#{data_pointer}`" case type @@ -14,8 +14,8 @@ def message keys = details.fetch('missing_keys', []).join(', ') "object at #{location} is missing required properties: #{keys}" when 'dependentRequired' - keys = details.fetch('missing_keys').join(', ') - "object at #{location} is missing required properties: #{keys}" + keys = details&.fetch('missing_keys') + "object at #{location} is missing required properties#{keys && " #{keys.join(', ')}"}" when 'string', 'boolean', 'number' "value at #{location} is not a #{type}" when 'array', 'object', 'integer' diff --git a/spec/schema/validation_result_spec.rb b/spec/schema/validation_result_spec.rb new file mode 100644 index 00000000..be41b8d8 --- /dev/null +++ b/spec/schema/validation_result_spec.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +RSpec.describe OpenapiFirst::Schema::ValidationResult do + def schema(hash) + JSONSchemer.schema(hash) + end + + describe 'missing required field' do + specify do + validation = schema({ required: ['id'] }).validate({}) + expect(described_class.new(validation).errors.first.message).to eq 'object at root is missing required properties: id' + end + end + + describe 'missing dependentRequired field' do + specify do + validation = schema({ 'dependentRequired' => { 'id' => ['type'] } }).validate({ 'id' => '2' }) + expect(described_class.new(validation).errors.first.message).to eq 'object at `/id` is missing required properties' + end + end +end