Skip to content

Commit

Permalink
Add schema validation against OpenAPI3 specification
Browse files Browse the repository at this point in the history
  • Loading branch information
numbata committed Jul 14, 2024
1 parent dcecc68 commit 00ed99e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ group :development, :test do
gem 'rdoc'
gem 'rspec', '~> 3.9'
gem 'rubocop', '~> 1.50', require: false
gem "openapi3_parser", "~> 0.10.0"

unless ENV['MODEL_PARSER'] == 'grape-swagger-entity'
gem 'grape-swagger-entity', git: 'https://github.com/ruby-grape/grape-swagger-entity'
Expand Down
9 changes: 9 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@
config.include ApiClassDefinitionCleaner
config.raise_errors_for_deprecations!

config.define_derived_metadata(file_path: /spec\/openapi_3/) do |metadata|
metadata[:type] ||= :openapi3
end
config.define_derived_metadata(file_path: /spec\/swagger_v2/) do |metadata|
metadata[:type] ||= :swagger2
end

config.include OpenAPI3ResponseValidationHelper, type: :openapi3

config.order = 'random'
config.seed = 40_834
end
35 changes: 35 additions & 0 deletions spec/support/open3_response_validation_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

require 'openapi3_parser'

# This module helps to validate the response body of endpoint tests
# against an OpenAPI 3.0 schema.
module OpenAPI3ResponseValidationHelper
include RSpec::Matchers

# Sets up an `after` hook to validate the response after each test example.
#
# @param base [Class] the class including this module
def self.included(base)
base.after(:each) do
next unless last_response
next unless last_response.ok?

validate_openapi3_response(last_response.body)
end
end

# Validates the response body against an OpenAPI 3.0 schema.
#
# @param response_body [String] the response body to be validated
def validate_openapi3_response(response_body)
document = Openapi3Parser.load(response_body)
return if document.valid?

aggregate_failures 'validation against an OpenAPI3' do
document.errors.errors.each do |error|
expect(document.valid?).to be(true), "#{error.message} in context #{error.context}"
end
end
end
end

0 comments on commit 00ed99e

Please sign in to comment.