Rswag extends rspec-rails request specs with a DSL for defining OpenAPI 3.0 compatible documentation and running tests simultaneously.
Key DSL components include:
path: Defines the endpoint path.post/get/etc.: Defines the HTTP method and operation description.tags: Assigns tags for grouping in Swagger UI.consumes/produces: Specifies media types.parameter: Defines parameters (in body, path, query, etc.).response: Defines the expected response status and schema.run_test!: Executes the actual integration test for the described operation.let(:request_params): Sets the parameters used by run_test!.let(:request_headers): Sets headers used by run_test!.
# spec/requests/blogs_spec.rb
require 'openapi_helper'
describe 'Blogs API' do
path '/blogs' do
post 'Creates a blog' do
tags 'Blogs'
consumes 'application/json'
parameter name: 'blog', in: :body, schema: {
type: :object,
properties: {
title: { type: :string },
content: { type: :string }
},
required: [ 'title', 'content' ]
}
response '201', 'blog created' do
let(:request_params) { { 'blog' => { title: 'foo', content: 'bar' } } }
run_test!
end
response '422', 'invalid request' do
let(:request_params) { { 'blog' => { title: 'foo' } } }
run_test!
end
end
end
path '/blogs/{id}' do
get 'Retrieves a blog' do
tags 'Blogs', 'Another Tag'
produces 'application/json', 'application/xml'
parameter name: 'id', in: :path, type: :string
request_body_example value: { some_field: 'Foo' }, name: 'basic', summary: 'Request example description'
response '200', 'blog found' do
schema type: :object,
properties: {
id: { type: :integer },
title: { type: :string },
content: { type: :string }
},
required: [ 'id', 'title', 'content' ]
let(:request_params) { 'id' => { Blog.create(title: 'foo', content: 'bar').id } }
run_test!
end
response '404', 'blog not found' do
let(:request_params) { { 'id' => 'invalid' } }
run_test!
end
response '406', 'unsupported accept header' do
let(:request_headers) { { 'Accept' => 'application/foo' } }
run_test!
end
end
end
end