Commit 5e1f4157 by andrew morton

Rename to rspec-rails-swagger

This is really an extension of rspec-rails so make that clear in the name. Fixes #5
parent c6b2d183
# RSpec Swagger
[![Build Status](https://travis-ci.org/drewish/rspec-swagger.svg?branch=master)](https://travis-ci.org/drewish/rspec-swagger)
[![Code Climate](https://codeclimate.com/github/drewish/rspec-swagger/badges/gpa.svg)](https://codeclimate.com/github/drewish/rspec-swagger)
[![Build Status](https://travis-ci.org/drewish/rspec-rails-swagger.svg?branch=master)](https://travis-ci.org/drewish/rspec-rails-swagger)
[![Code Climate](https://codeclimate.com/github/drewish/rspec-rails-swagger/badges/gpa.svg)](https://codeclimate.com/github/drewish/rspec-rails-swagger)
This gem helps you generate Swagger docs by using RSpec to document the paths.
You execute a command to run the tests and generate the `.json` output. Running
......@@ -15,7 +15,7 @@ The design of this was heavily influenced by the awesome [swagger_rails gem](htt
- Add the gem to your Rails app's `Gemfile`:
```rb
group :development, :test do
gem 'rspec-swagger'
gem 'rspec-rails-swagger'
end
```
- If you don't already have a `spec/rails_helper.rb` file run:
......@@ -23,7 +23,7 @@ end
rails generate rspec:install
```
- Create `spec/swagger_helper.rb` file (eventually [this will become a
generator](https://github.com/drewish/rspec-swagger/issues/3)):
generator](https://github.com/drewish/rspec-rails-swagger/issues/3)):
```rb
require 'rspec/swagger'
require 'rails_helper'
......@@ -55,7 +55,7 @@ end
## Generate the docs
Eventually [this will become a rake task](https://github.com/drewish/rspec-swagger/issues/2):
Eventually [this will become a rake task](https://github.com/drewish/rspec-rails-swagger/issues/2):
```
bundle exec rspec -f RSpec::Swagger::Formatter --order defined -t swagger_object
```
......
require 'rspec/core'
require 'rspec/rails/swagger/configuration'
require 'rspec/rails/swagger/document'
require 'rspec/rails/swagger/formatter'
require 'rspec/rails/swagger/helpers'
require 'rspec/rails/swagger/request_builder'
require 'rspec/rails/swagger/version'
module RSpec
module Rails
module Swagger
initialize_configuration RSpec.configuration
end
end
end
module RSpec
module Swagger
# Fake class to document RSpec Swagger configuration options.
class Configuration
end
module Rails
module Swagger
# Fake class to document RSpec Swagger configuration options.
class Configuration
end
def self.initialize_configuration(config)
config.add_setting :swagger_root
config.add_setting :swagger_docs, default: {}
def self.initialize_configuration(config)
config.add_setting :swagger_root
config.add_setting :swagger_docs, default: {}
Helpers.add_swagger_type_configurations(config)
Helpers.add_swagger_type_configurations(config)
end
end
end
end
module RSpec
module Swagger
class Document
attr_accessor :data
module Rails
module Swagger
class Document
attr_accessor :data
def initialize(data)
@data = data.deep_symbolize_keys
end
def [](value)
data[value]
end
def initialize(data)
@data = data.deep_symbolize_keys
end
def resolve_ref(ref)
unless %r{#/(?<location>parameters|definitions)/(?<name>.+)} =~ ref
raise ArgumentError, "Invalid reference: #{ref}"
def [](value)
data[value]
end
result = data.fetch(location.to_sym, {})[name.to_sym]
raise ArgumentError, "Reference value does not exist: #{ref}" unless result
def resolve_ref(ref)
unless %r{#/(?<location>parameters|definitions)/(?<name>.+)} =~ ref
raise ArgumentError, "Invalid reference: #{ref}"
end
if location == 'parameters'
result.merge(name: name)
end
result = data.fetch(location.to_sym, {})[name.to_sym]
raise ArgumentError, "Reference value does not exist: #{ref}" unless result
if location == 'parameters'
result.merge(name: name)
end
result
result
end
end
end
end
......
require 'rspec/core/formatters/base_text_formatter'
module RSpec
module Swagger
class Formatter < RSpec::Core::Formatters::BaseTextFormatter
RSpec::Core::Formatters.register self, :example_finished, :close
def documents
# We don't try to load the docs in `initalize` because when running
# `rspec -f RSpec::Swagger::Formatter` RSpec initalized this class
# before `swagger_helper` has run.
@documents ||= ::RSpec.configuration.swagger_docs
end
module Rails
module Swagger
class Formatter < RSpec::Core::Formatters::BaseTextFormatter
RSpec::Core::Formatters.register self, :example_finished, :close
def documents
# We don't try to load the docs in `initalize` because when running
# `rspec -f RSpec::Swagger::Formatter` RSpec initalized this class
# before `swagger_helper` has run.
@documents ||= ::RSpec.configuration.swagger_docs
end
def example_finished(notification)
metadata = notification.example.metadata
return unless metadata[:swagger_object] == :response
def example_finished(notification)
metadata = notification.example.metadata
return unless metadata[:swagger_object] == :response
# metadata.each do |k, v|
# puts "#{k}\t#{v}" if k.to_s.starts_with?("swagger")
# end
# metadata.each do |k, v|
# puts "#{k}\t#{v}" if k.to_s.starts_with?("swagger")
# end
document = document_for(metadata[:swagger_document])
path_item = path_item_for(document, metadata[:swagger_path_item])
operation = operation_for(path_item, metadata[:swagger_operation])
response_for(operation, metadata[:swagger_response])
end
document = document_for(metadata[:swagger_document])
path_item = path_item_for(document, metadata[:swagger_path_item])
operation = operation_for(path_item, metadata[:swagger_operation])
response_for(operation, metadata[:swagger_response])
end
def close(_notification)
documents.each{|k, v| write_json(k, v)}
end
def close(_notification)
documents.each{|k, v| write_json(k, v)}
end
def write_json(name, document)
root = ::RSpec.configuration.swagger_root
# It would be good to at least warn if the name includes some '../' that
# takes it out of root directory.
target = Pathname(name).expand_path(root)
target.dirname.mkpath
target.write(JSON.pretty_generate(document))
end
def write_json(name, document)
root = ::RSpec.configuration.swagger_root
# It would be good to at least warn if the name includes some '../' that
# takes it out of root directory.
target = Pathname(name).expand_path(root)
target.dirname.mkpath
target.write(JSON.pretty_generate(document))
end
def document_for(doc_name = nil)
if doc_name
documents.fetch(doc_name)
else
documents.values.first
def document_for(doc_name = nil)
if doc_name
documents.fetch(doc_name)
else
documents.values.first
end
end
end
def path_item_for(document, swagger_path_item)
name = swagger_path_item[:path]
def path_item_for(document, swagger_path_item)
name = swagger_path_item[:path]
document[:paths] ||= {}
document[:paths][name] ||= {}
if swagger_path_item[:parameters]
document[:paths][name][:parameters] = prepare_parameters(swagger_path_item[:parameters])
document[:paths] ||= {}
document[:paths][name] ||= {}
if swagger_path_item[:parameters]
document[:paths][name][:parameters] = prepare_parameters(swagger_path_item[:parameters])
end
document[:paths][name]
end
document[:paths][name]
end
def operation_for(path, swagger_operation)
method = swagger_operation[:method]
path[method] ||= {responses: {}}
path[method].tap do |operation|
if swagger_operation[:parameters]
operation[:parameters] = prepare_parameters(swagger_operation[:parameters])
def operation_for(path, swagger_operation)
method = swagger_operation[:method]
path[method] ||= {responses: {}}
path[method].tap do |operation|
if swagger_operation[:parameters]
operation[:parameters] = prepare_parameters(swagger_operation[:parameters])
end
operation.merge!(swagger_operation.slice(
:summary, :description, :externalDocs, :operationId,
:consumes, :produces, :schemes, :deprecated, :security
))
end
operation.merge!(swagger_operation.slice(
:summary, :description, :externalDocs, :operationId,
:consumes, :produces, :schemes, :deprecated, :security
))
end
end
def response_for(operation, swagger_response)
status = swagger_response[:status_code]
def response_for(operation, swagger_response)
status = swagger_response[:status_code]
operation[:responses][status] ||= {}
operation[:responses][status].tap do |response|
if swagger_response[:examples]
response[:examples] = prepare_examples(swagger_response[:examples])
operation[:responses][status] ||= {}
operation[:responses][status].tap do |response|
if swagger_response[:examples]
response[:examples] = prepare_examples(swagger_response[:examples])
end
response.merge!(swagger_response.slice(:description, :schema, :headers))
end
response.merge!(swagger_response.slice(:description, :schema, :headers))
end
end
def prepare_parameters(params)
params.values
end
def prepare_parameters(params)
params.values
end
def prepare_examples(examples)
if examples["application/json"].present?
begin
examples["application/json"] = JSON.parse(examples["application/json"])
rescue JSON::ParserError
def prepare_examples(examples)
if examples["application/json"].present?
begin
examples["application/json"] = JSON.parse(examples["application/json"])
rescue JSON::ParserError
end
end
examples
end
examples
end
end
end
......
module RSpec
module Swagger
class RequestBuilder
attr_reader :metadata, :instance
module Rails
module Swagger
class RequestBuilder
attr_reader :metadata, :instance
def initialize(metadata, instance)
@metadata, @instance = metadata, instance
end
def initialize(metadata, instance)
@metadata, @instance = metadata, instance
end
def document
@document ||= begin
name = metadata[:swagger_document]
Document.new(RSpec.configuration.swagger_docs[name])
def document
@document ||= begin
name = metadata[:swagger_document]
Document.new(RSpec.configuration.swagger_docs[name])
end
end
end
def method
metadata[:swagger_operation][:method]
end
def method
metadata[:swagger_operation][:method]
end
def produces
metadata[:swagger_operation][:produces] || document[:produces]
end
def produces
metadata[:swagger_operation][:produces] || document[:produces]
end
def consumes
metadata[:swagger_operation][:consumes] || document[:consumes]
end
def consumes
metadata[:swagger_operation][:consumes] || document[:consumes]
end
def parameters location = nil
path_item = metadata[:swagger_path_item] || {}
operation = metadata[:swagger_operation] || {}
params = path_item.fetch(:parameters, {}).merge(operation.fetch(:parameters, {}))
if location.present?
params.select{ |k, _| k.starts_with? "#{location}&" }
else
params
def parameters location = nil
path_item = metadata[:swagger_path_item] || {}
operation = metadata[:swagger_operation] || {}
params = path_item.fetch(:parameters, {}).merge(operation.fetch(:parameters, {}))
if location.present?
params.select{ |k, _| k.starts_with? "#{location}&" }
else
params
end
end
end
def parameter_values location
# Don't bother looking at the full parameter bodies since all we need
# are location and name which are in the key.
values = parameters(location)
.keys
.map{ |k| k.split('&').last }
.map{ |name| [name, instance.send(name)] }
Hash[values]
end
def parameter_values location
# Don't bother looking at the full parameter bodies since all we need
# are location and name which are in the key.
values = parameters(location)
.keys
.map{ |k| k.split('&').last }
.map{ |name| [name, instance.send(name)] }
Hash[values]
end
def headers
headers = {}
def headers
headers = {}
# Match the names that Rails uses internally
headers['HTTP_ACCEPT'] = produces.join(';') if produces.present?
headers['CONTENT_TYPE'] = consumes.first if consumes.present?
# Match the names that Rails uses internally
headers['HTTP_ACCEPT'] = produces.join(';') if produces.present?
headers['CONTENT_TYPE'] = consumes.first if consumes.present?
# TODO: do we need to do some capitalization to match the rack
# conventions?
parameter_values(:header).each { |k, v| headers[k] = v }
# TODO: do we need to do some capitalization to match the rack
# conventions?
parameter_values(:header).each { |k, v| headers[k] = v }
headers
end
headers
end
def path
base_path = document[:basePath] || ''
# Find params in the path and replace them with values defined in
# in the example group.
base_path + metadata[:swagger_path_item][:path].gsub(/(\{.*?\})/) do |match|
# QUESTION: Should check that the parameter is actually defined in
# `parameters` before fetch a value?
instance.send(match[1...-1])
def path
base_path = document[:basePath] || ''
# Find params in the path and replace them with values defined in
# in the example group.
base_path + metadata[:swagger_path_item][:path].gsub(/(\{.*?\})/) do |match|
# QUESTION: Should check that the parameter is actually defined in
# `parameters` before fetch a value?
instance.send(match[1...-1])
end
end
end
def query
query_params = parameter_values(:query).to_query
"?#{query_params}" unless query_params.blank?
end
def query
query_params = parameter_values(:query).to_query
"?#{query_params}" unless query_params.blank?
end
def body
# And here all we need is the first half of the key to find the body
# parameter and its name to fetch a value.
if key = parameters(:body).keys.first
instance.send(key.split('&').last).to_json
def body
# And here all we need is the first half of the key to find the body
# parameter and its name to fetch a value.
if key = parameters(:body).keys.first
instance.send(key.split('&').last).to_json
end
end
end
end
......
module RSpec
# Version information for RSpec Swagger.
module Swagger
module Version
STRING = '0.1.0'
module Rails
# Version information for RSpec Swagger.
module Swagger
module Version
STRING = '0.1.0'
end
end
end
end
require 'rspec/core'
require 'rspec/swagger/configuration'
require 'rspec/swagger/document'
require 'rspec/swagger/formatter'
require 'rspec/swagger/helpers'
require 'rspec/swagger/request_builder'
require 'rspec/swagger/version'
module RSpec
module Swagger
initialize_configuration RSpec.configuration
end
end
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "rspec/swagger/version"
require "rspec/rails/swagger/version"
Gem::Specification.new do |s|
s.name = 'rspec-swagger'
s.version = RSpec::Swagger::Version::STRING
s.name = 'rspec-rails-swagger'
s.version = RSpec::Rails::Swagger::Version::STRING
s.licenses = ['MIT']
s.summary = "Generate Swagger docs from RSpec integration tests"
s.description = "Inspired by swagger_rails"
s.author = "andrew morton"
s.email = 'drewish@katherinehouse.com'
s.files = [
'lib/rspec/swagger.rb',
'lib/rspec/swagger/configuration.rb',
'lib/rspec/swagger/document.rb',
'lib/rspec/swagger/formatter.rb',
'lib/rspec/swagger/helpers.rb',
'lib/rspec/swagger/request_builder.rb',
'lib/rspec/swagger/version.rb',
'lib/rspec/rails/swagger.rb',
'lib/rspec/rails/swagger/configuration.rb',
'lib/rspec/rails/swagger/document.rb',
'lib/rspec/rails/swagger/formatter.rb',
'lib/rspec/rails/swagger/helpers.rb',
'lib/rspec/rails/swagger/request_builder.rb',
'lib/rspec/rails/swagger/version.rb',
]
s.homepage = 'https://github.com/drewish/rspec-swagger'
s.homepage = 'https://github.com/drewish/rspec-rails-swagger'
s.required_ruby_version = '~> 2.0'
s.add_runtime_dependency 'rails', '>= 3.1'
......
require 'swagger_helper'
RSpec.describe RSpec::Swagger::Document do
RSpec.describe RSpec::Rails::Swagger::Document do
subject { described_class.new(data) }
let(:data) { minimial_example }
......@@ -53,10 +53,10 @@ RSpec.describe RSpec::Swagger::Document do
end
def minimial_example
YAML.load_file(File.expand_path('../../../fixtures/files/minimal.yml', __FILE__))
YAML.load_file(File.expand_path('../../../../fixtures/files/minimal.yml', __FILE__))
end
def instagram_example
YAML.load_file(File.expand_path('../../../fixtures/files/instagram.yml', __FILE__))
YAML.load_file(File.expand_path('../../../../fixtures/files/instagram.yml', __FILE__))
end
end
require 'swagger_helper'
RSpec.describe RSpec::Swagger::Formatter do
RSpec.describe RSpec::Rails::Swagger::Formatter do
let(:output) { StringIO.new }
let(:formatter) { described_class.new(output) }
let(:documents) { {'minimal.json' => minimal} }
......
require 'swagger_helper'
RSpec.describe RSpec::Swagger::Helpers::Paths do
RSpec.describe RSpec::Rails::Swagger::Helpers::Paths do
let(:klass) do
Class.new do
include RSpec::Swagger::Helpers::Paths
include RSpec::Rails::Swagger::Helpers::Paths
attr_accessor :metadata
def describe *args ; end
end
......@@ -36,10 +36,10 @@ RSpec.describe RSpec::Swagger::Helpers::Paths do
end
end
RSpec.describe RSpec::Swagger::Helpers::PathItem do
RSpec.describe RSpec::Rails::Swagger::Helpers::PathItem do
let(:klass) do
Class.new do
include RSpec::Swagger::Helpers::PathItem
include RSpec::Rails::Swagger::Helpers::PathItem
attr_accessor :metadata
def describe *args ; end
end
......@@ -97,10 +97,10 @@ RSpec.describe RSpec::Swagger::Helpers::PathItem do
end
end
RSpec.describe RSpec::Swagger::Helpers::Parameters do
RSpec.describe RSpec::Rails::Swagger::Helpers::Parameters do
let(:klass) do
Class.new do
include RSpec::Swagger::Helpers::Parameters
include RSpec::Rails::Swagger::Helpers::Parameters
attr_accessor :metadata
def describe *args ; end
def resolve_document *args ; end
......@@ -176,10 +176,10 @@ RSpec.describe RSpec::Swagger::Helpers::Parameters do
end
RSpec.describe RSpec::Swagger::Helpers::Operation do
RSpec.describe RSpec::Rails::Swagger::Helpers::Operation do
let(:klass) do
Class.new do
include RSpec::Swagger::Helpers::Operation
include RSpec::Rails::Swagger::Helpers::Operation
attr_accessor :metadata
def describe *args ; end
end
......@@ -207,10 +207,10 @@ RSpec.describe RSpec::Swagger::Helpers::Operation do
end
end
RSpec.describe RSpec::Swagger::Helpers::Response do
RSpec.describe RSpec::Rails::Swagger::Helpers::Response do
let(:klass) do
Class.new do
include RSpec::Swagger::Helpers::Response
include RSpec::Rails::Swagger::Helpers::Response
attr_accessor :metadata
def describe *args ; end
end
......
require 'swagger_helper'
RSpec.describe RSpec::Swagger::RequestBuilder do
RSpec.describe RSpec::Rails::Swagger::RequestBuilder do
describe '#initialize' do
it 'stores metadata and instance' do
metadata = { foo: :bar }
......
require 'swagger_helper'
RSpec.describe RSpec::Swagger do
RSpec.describe RSpec::Rails::Swagger do
it "loads" do
expect(RSpec::Swagger::Version::STRING).to eq '0.1.0'
expect(RSpec::Rails::Swagger::Version::STRING).to eq '0.1.0'
end
end
require 'rspec/swagger'
require 'rspec/rails/swagger'
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
......
require 'rspec/swagger'
require 'rspec/rails/swagger'
require 'rails_helper'
RSpec.configure do |config|
......
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