Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error message when validating enum #116

Merged
merged 1 commit into from
Aug 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/openapi_first/validation_format.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ def self.error_details(error)
title: "has not a valid #{error.dig('schema', 'format')} format",
detail: "#{error['data'].inspect} is not a valid #{error.dig('schema', 'format')} format"
}
elsif error['type'] == 'enum'
{
title: "value #{error['data'].inspect} is not defined in enum",
detail: "value can be one of #{error.dig('schema', 'enum')&.join(', ')}"
}
elsif error['type'] == 'required'
missing_keys = error['details']['missing_keys']
{
Expand Down
3 changes: 3 additions & 0 deletions spec/data/petstore-expanded.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,9 @@ components:
properties:
type:
type: string
enum:
- pet
- plant
attributes:
additionalProperties: false
type: object
Expand Down
14 changes: 13 additions & 1 deletion spec/request_validation/request_body_validation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

let(:request_body) do
{
type: 'people',
type: 'pet',
attributes: {
name: 'Oscar'
}
Expand Down Expand Up @@ -92,6 +92,18 @@
expect(error[:source][:pointer]).to eq '/attributes'
end

it 'returns 400 if value is not defined in enum' do
request_body[:type] = 'unknown-type'
header Rack::CONTENT_TYPE, 'application/json'
post path, json_dump(request_body)

expect(last_response.status).to be 400
error = response_body[:errors][0]
expect(error[:title]).to eq 'value "unknown-type" is not defined in enum'
expect(error[:source][:pointer]).to eq '/type'
expect(error[:detail]).to eq 'value can be one of pet, plant'
end

it 'returns 400 if additional property is not allowed' do
request_body[:attributes].update(foo: :bar)
header Rack::CONTENT_TYPE, 'application/json'
Expand Down