Generate OpenAPI schema from RSpec request specs
Generate OpenAPI schema from RSpec request specs
Generate OpenAPI schema from RSpec request specs.
There are some gems which generate OpenAPI specs from RSpec request specs. However, they require a special DSL specific to these gems, and we can't reuse existing request specs as they are.
Unlike such existing gems, rspec-openapi can generate OpenAPI specs from request specs without requiring any special DSL. Furthermore, rspec-openapi keeps manual modifications when it merges automated changes to OpenAPI specs in case we can't generate everything from request specs.
Add this line to your application's Gemfile:
gem 'rspec-openapi', group: :testRun rspec with OPENAPI=1 to generate doc/openapi.yaml for your request specs.
$ OPENAPI=1 bundle exec rspecLet's say you have a request spec like this:
RSpec.describe 'Tables', type: :request do
describe '#index' do
it 'returns a list of tables' do
get '/tables', params: { page: '1', per: '10' }, headers: { authorization: 'k0kubun' }
expect(response.status).to eq(200)
end
it 'does not return tables if unauthorized' do
get '/tables'
expect(response.status).to eq(401)
end
end
# ...
endIf you run the spec with OPENAPI=1,
OPENAPI=1 bundle exec rspec spec/requests/tables_spec.rbIt will generate doc/openapi.yaml file like:
…and the schema file can be used as an input of Swagger UI or Redoc.
The following configurations are optional.
…The generated openapi version defaults to 3.2.0 (the latest). OpenAPI 3.1+ is aligned with
JSON Schema 2020-12, so nullable values are expressed via the type array instead of the nullable keyword.
# 3.0 (set RSpec::OpenAPI.openapi_version = '3.0.x')
name:
type: string
nullable: true# 3.1 (set RSpec::OpenAPI.openapi_version = '3.1.x')
# 3.2 (set RSpec::OpenAPI.openapi_version = '3.2.x')
name:
type:
- string
- nullRSpec::OpenAPI.openapi_version to a 3.0.x string to keep the previous nullable: true output.3.1.x string produces the same schema shapes as the default 3.2.0; they differ only in the reported
version and the 3.2-only constructs described below (query / additionalOperations / itemSchema).Upgrade note: an existing file is read regardless of its version, so the first OPENAPI=1 run after upgrading
rewrites it to the new default (e.g. 3.0.3 -> 3.2.0, nullable: true -> a null type). Pin
RSpec::OpenAPI.openapi_version = '3.0.3' to opt out.
| Feature | OpenAPI 3.0.x | 3.1.x | 3.2.x (default) |
|---|---|---|---|
| Core generation (paths / schemas / examples) | ✓ | ✓ | ✓ |
| Null representation | nullable: true |
type array [..., 'null'] |
type array [..., 'null'] |
Structured root tags (summary / parent / kind) |
name only | name only | ✓ |
query field (QUERY method) |
— | — | ✓ |
additionalOperations (non-standard verbs: COPY, MOVE, …) |
— | — | ✓ |
Streaming itemSchema (jsonl / ndjson / json-seq / SSE) |
— | — | ✓ |
$ref to minimize duplication of schema?Yes, rspec-openapi v0.7.0+ supports $ref mechanism and generates
schemas under #/components/schemas with some manual steps.
$ref.paths:
"/users":
get:
responses:
'200':
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/User"
"/users/{id}":
get:
responses:
'200':
content:
application/json:
schema:
$ref: "#/components/schemas/User"
# Note) #/components/schemas is not needed to be defined.#/components/schemas with the referenced schema (User for example)
newly-generated or updated.…rspec-openapi also supports $ref in properties of schemas. Example)
paths:
"/locations":
get:
responses:
'200':
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Location"
components:
schemas:
Location:
type: object
properties:
id:
type: string
name:
type: string
Coordinate:
"$ref": "#/components/schemas/Coordinate"
Coordinate:
type: object
properties:
lat:
type: string
lon:
type: stringNote that automatic schemas update feature is still new and may not work in complex scenario.
If you find a room for improvement, open an issue.
rspec-openapi tries to preserve manual modifications as much as possible when generating specs.
You can directly edit doc/openapi.yaml as you like without spoiling the automatic generation capability.
Yes, you can specify openapi: false to disable the automatic generation.
RSpec.describe '/resources', type: :request, openapi: false do
# ...
end
# or
RSpec.describe '/resources', type: :request do
it 'returns a resource', openapi: false do
# ...
end
endSome examples' attributes can be overwritten via RSpec metadata options. Example:
describe 'GET /api/v1/posts', openapi: {
summary: 'list all posts',
description: 'list all posts ordered by pub_date',
tags: %w[v1 posts],
required_request_params: %w[limit],
security: [{ "MyToken" => [] }],
} do
# ...
endNOTE: description key will override also the one provided by RSpec::OpenAPI.description_builder method.
openapi: metadataopenapi: metadata is inherited from the surrounding describe/context groups down to each
example, at any nesting depth. Inner levels override outer ones key by key, so a nested group only
needs to declare the keys it wants to change:
describe 'GET /tables', openapi: { summary: 'Get a list of tables', tags: %w[Table] } do
context 'with pagination', openapi: { example_mode: :multiple } do
# This example inherits summary: 'Get a list of tables' and tags: ['Table']
# from the outer describe, and adds example_mode: :multiple.
it { get '/tables', params: { page: 1 } }
end
endThe merge happens at the top level of the openapi: hash. Scalar keys (summary, operation_id,
…) follow last-wins, and a nested level that re-declares a structured key (tags, security,
enum, …) replaces the inherited value for that key rather than deep-merging it.
request_pattern)By default rspec-openapi documents the last request/response exchange issued in an example.
When a single example performs several requests on the same path (for example a DELETE
followed by a GET that asserts the resource is gone), that trailing request would otherwise
overwrite the operation you actually want to document.
Use the request_pattern metadata to pick the exchange explicitly. Its value is a
" " string, where the path may use {param} placeholders:
describe 'Deleting a widget',
openapi: { summary: 'Delete a widget', request_pattern: 'DELETE /widgets/{id}' } do
it 'deletes the widget and verifies it is gone' do
delete '/widgets/1'
expect(response.status).to eq(200)
# Without request_pattern this trailing GET would become the documented
# exchange; the selector keeps the DELETE above as the operation instead.
get '/widgets/1?missing=1'
expect(response.status).to eq(404)
end
end{param} placeholder matches a single path segment independently, so multi-segment
templates such as 'DELETE /orgs/{org_id}/members/{user_id}' work as expected.ActionDispatch::IntegrationTest) and Rack::Test-based specs
(e.g. Roda, Hanami).You can specify enum values for string properties that should have a fixed set of allowed values. Since enums cannot be
reliably inferred from test data, you can define them via the enum metadata option:
it 'returns user status', openapi: {
enum: {
'status' => %w[active inactive suspended],
},
} do
get '/users/1'
expect(response.status).to eq(200)
endThis generates:
schema:
type: object
properties:
status:
type: string
enum:
- active
- inactive
- suspendedFor nested objects, use dot notation to specify the path:
it 'returns user with role', openapi: {
enum: {
'status' => %w[active inactive],
'user.role' => %w[admin user guest],
},
} do
get '/teams/1'
# Response: { "status": "active", "user": { "name": "John", "role": "admin" } }
expect(response.status).to eq(200)
endFor properties inside array items, use the array property name followed by the item property:
it 'returns items with status', openapi: {
enum: {
'items.status' => %w[pending completed failed],
'items.priority' => %w[high medium low],
},
} do
get '/tasks'
# Response: { "items": [{ "id": 1, "status": "pending", "priority": "high" }] }
expect(response.status).to eq(200)
endBy default, enum applies to both request and response bodies. If you need different enum values for request and
response, use request_enum and response_enum:
it 'creates a task', openapi: {
request_enum: {
'action' => %w[create update delete],
},
response_enum: {
'status' => %w[pending processing completed],
},
} do
post '/tasks', params: { action: 'create', name: 'New Task' }
expect(response.status).to eq(201)
endadditionalProperties)When an endpoint returns (or accepts) an object whose keys are not part of its
schema — for example a permissions map { "can_edit": true, "can_delete": false }
where new permissions can appear without an API change — rspec-openapi would
otherwise capture the test response literally and emit each observed key as a
fixed property. You can override this with the additional_properties metadata,
which replaces the captured properties / required of the matched object with
additionalProperties.
Keys are dot-notation paths (the same scheme as enum); the empty string ''
targets the body root.
it 'returns a permission map', openapi: {
additional_properties: { 'data' => { type: 'boolean' } },
} do
get '/api/v1/permissions'
# Response: { "data": { "can_edit": true, "can_delete": false } }
expect(response.status).to eq(200)
endThis generates:
schema:No open issues yet, or sync has not completed.