Skip to content

Commit 00ed99e

Browse files
committed
Add schema validation against OpenAPI3 specification
1 parent dcecc68 commit 00ed99e

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ group :development, :test do
3232
gem 'rdoc'
3333
gem 'rspec', '~> 3.9'
3434
gem 'rubocop', '~> 1.50', require: false
35+
gem "openapi3_parser", "~> 0.10.0"
3536

3637
unless ENV['MODEL_PARSER'] == 'grape-swagger-entity'
3738
gem 'grape-swagger-entity', git: 'https://github.com/ruby-grape/grape-swagger-entity'

spec/spec_helper.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@
2828
config.include ApiClassDefinitionCleaner
2929
config.raise_errors_for_deprecations!
3030

31+
config.define_derived_metadata(file_path: /spec\/openapi_3/) do |metadata|
32+
metadata[:type] ||= :openapi3
33+
end
34+
config.define_derived_metadata(file_path: /spec\/swagger_v2/) do |metadata|
35+
metadata[:type] ||= :swagger2
36+
end
37+
38+
config.include OpenAPI3ResponseValidationHelper, type: :openapi3
39+
3140
config.order = 'random'
3241
config.seed = 40_834
3342
end
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
require 'openapi3_parser'
4+
5+
# This module helps to validate the response body of endpoint tests
6+
# against an OpenAPI 3.0 schema.
7+
module OpenAPI3ResponseValidationHelper
8+
include RSpec::Matchers
9+
10+
# Sets up an `after` hook to validate the response after each test example.
11+
#
12+
# @param base [Class] the class including this module
13+
def self.included(base)
14+
base.after(:each) do
15+
next unless last_response
16+
next unless last_response.ok?
17+
18+
validate_openapi3_response(last_response.body)
19+
end
20+
end
21+
22+
# Validates the response body against an OpenAPI 3.0 schema.
23+
#
24+
# @param response_body [String] the response body to be validated
25+
def validate_openapi3_response(response_body)
26+
document = Openapi3Parser.load(response_body)
27+
return if document.valid?
28+
29+
aggregate_failures 'validation against an OpenAPI3' do
30+
document.errors.errors.each do |error|
31+
expect(document.valid?).to be(true), "#{error.message} in context #{error.context}"
32+
end
33+
end
34+
end
35+
end

0 commit comments

Comments
 (0)