Commit 89a8130e by Igor Makarov Committed by andrew morton

formatters for response examples (#33)

* formatters for response examples * code standard fixes
parent a3f4a1e0
......@@ -3,6 +3,7 @@ require 'rspec/rails/swagger/configuration'
require 'rspec/rails/swagger/document'
require 'rspec/rails/swagger/formatter'
require 'rspec/rails/swagger/helpers'
require 'rspec/rails/swagger/response_formatters'
require 'rspec/rails/swagger/request_builder'
require 'rspec/rails/swagger/route_parser'
require 'rspec/rails/swagger/version'
......
......@@ -130,12 +130,10 @@ module RSpec
end
def prepare_examples(examples)
if examples['application/json'].kind_of? String
begin
examples['application/json'] = JSON.parse(examples['application/json'])
rescue JSON::ParserError
end
examples.each_pair do |format, resp|
examples[format] = ResponseFormatters[format].call(resp)
end
examples
end
end
......
module RSpec
module Rails
module Swagger
class ResponseFormatters
class JSON
def call(resp)
if resp.kind_of? String
::JSON.parse(resp)
else
resp
end
rescue ::JSON::ParserError
resp
end
end
@formatters = {
:default => ->(resp) { resp },
'application/json' => JSON.new
}
class << self
def register(format, callable)
@formatters[format] = callable
end
def [](key)
@formatters[key] || @formatters[:default]
end
end
end
end
end
end
......@@ -65,6 +65,53 @@ RSpec.describe RSpec::Rails::Swagger::Formatter do
expect(formatter.documents['doc2.json'][:paths].length).to eq(1)
end
end
context "with a response examples" do
let(:metadata_examples) { {'application/json' => JSON.dump({foo: :bar})} }
let(:metadata) do
{
swagger_object: :response,
swagger_path_item: {path: "/ping"},
swagger_operation: {method: :put},
swagger_response: {status_code: 200, description: "OK", examples: metadata_examples},
}
end
shared_examples 'response example formatter' do
it "copies the requests into the document" do
formatter.example_finished(example_notification)
expected_paths = {
'/ping' => {
put: {
responses: {200 => {examples: output_examples, description: 'OK'}}
}
}
}
expect(formatter.documents.values.first[:paths]).to eq(expected_paths)
end
end
context "with a default formatter" do
before(:example) do
RSpec::Rails::Swagger::ResponseFormatters.register(
'application/json',
RSpec::Rails::Swagger::ResponseFormatters::JSON.new
)
end
let(:output_examples) { {'application/json' => {"foo" => "bar"}} }
include_examples 'response example formatter'
end
context "custom application/json formatter" do
before(:example) do
RSpec::Rails::Swagger::ResponseFormatters.register('application/json', ->(resp) { resp })
end
let(:output_examples) { {'application/json' => JSON.dump({foo: :bar})} }
include_examples 'response example formatter'
end
end
end
describe "#close" do
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment