Response body value validation

Add the possibility to pass a block to the run_test!
method in order to add expectations on your response
This commit is contained in:
Horia Radu
2017-04-28 11:40:33 +03:00
parent cf9170101b
commit 51c9f4e5e6
7 changed files with 44 additions and 11 deletions

View File

@@ -69,7 +69,7 @@ module Rswag
metadata[:response][:examples] = example
end
def run_test!
def run_test!(&block)
# NOTE: rspec 2.x support
if RSPEC_VERSION < 3
before do
@@ -77,7 +77,7 @@ module Rswag
end
it "returns a #{metadata[:response][:code]} response" do
assert_response_matches_metadata(example.metadata)
assert_response_matches_metadata(example.metadata, &block)
end
else
before do |example|
@@ -85,7 +85,7 @@ module Rswag
end
it "returns a #{metadata[:response][:code]} response" do |example|
assert_response_matches_metadata(example.metadata)
assert_response_matches_metadata(example.metadata, &block)
end
end
end

View File

@@ -28,10 +28,10 @@ module Rswag
end
end
def assert_response_matches_metadata(api_metadata)
def assert_response_matches_metadata(api_metadata, &block)
global_metadata = rswag_config.get_swagger_doc(api_metadata[:swagger_doc])
validator = ResponseValidator.new(api_metadata, global_metadata)
validator.validate!(response)
validator.validate!(response, &block)
end
private

View File

@@ -1,5 +1,6 @@
require 'active_support/core_ext/hash/slice'
require 'json-schema'
require 'json'
require 'rswag/specs/extended_schema'
module Rswag
@@ -11,10 +12,10 @@ module Rswag
@global_metadata = global_metadata
end
def validate!(response)
def validate!(response, &block)
validate_code!(response.code)
validate_headers!(response.headers)
validate_body!(response.body)
validate_body!(response.body, &block)
end
private
@@ -34,7 +35,7 @@ module Rswag
end
end
def validate_body!(body)
def validate_body!(body, &block)
response_schema = @api_metadata[:response][:schema]
return if response_schema.nil?
@@ -46,6 +47,8 @@ module Rswag
rescue JSON::Schema::ValidationError => ex
raise UnexpectedResponse, "Expected response body to match schema: #{ex.message}"
end
block.call(JSON.parse(body)) if block_given?
end
end