百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rspec-openapi

> 后端框架
开源

从 RSPEC 请求创建 OpenAPI 计划

508 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

从 RSPEC 请求创建 OpenAPI 计划

rspec-openapi

Generate OpenAPI schema from RSpec request specs.

What's this?

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.

Installation

Add this line to your application's Gemfile:

ruby
gem 'rspec-openapi', group: :test

Usage

Run rspec with OPENAPI=1 to generate doc/openapi.yaml for your request specs.

bash
$ OPENAPI=1 bundle exec rspec

Example

Let's say you have a request spec like this:

rb
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

  # ...
end

If you run the spec with OPENAPI=1,

OPENAPI=1 bundle exec rspec spec/requests/tables_spec.rb

It will generate doc/openapi.yaml file like:

…

and the schema file can be used as an input of Swagger UI or Redoc.

Configuration

The following configurations are optional.

…

OpenAPI version

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.

yaml
# 3.0 (set RSpec::OpenAPI.openapi_version = '3.0.x')
name:
  type: string
  nullable: true
yaml
# 3.1 (set RSpec::OpenAPI.openapi_version = '3.1.x')
# 3.2 (set RSpec::OpenAPI.openapi_version = '3.2.x')
name:
  type:
  - string
  - null
  • Set RSpec::OpenAPI.openapi_version to a 3.0.x string to keep the previous nullable: true output.
  • A 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.

Supported OpenAPI features

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) — — ✓

Can I use rspec-openapi with $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.

  1. First, generate plain OpenAPI file.
  2. Then, manually replace the duplications with $ref.
yaml
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.
  1. Then, re-run rspec-openapi. It will generate #/components/schemas with the referenced schema (User for example) newly-generated or updated.
…

rspec-openapi also supports $ref in properties of schemas. Example)

yaml
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: string

Note 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.

How can I add information which can't be generated from RSpec?

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.

Can I exclude specific specs from OpenAPI generation?

Yes, you can specify openapi: false to disable the automatic generation.

rb
RSpec.describe '/resources', type: :request, openapi: false do
  # ...
end

# or

RSpec.describe '/resources', type: :request do
  it 'returns a resource', openapi: false do
    # ...
  end
end

Customizations

Some examples' attributes can be overwritten via RSpec metadata options. Example:

rb
  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
  # ...
end

NOTE: description key will override also the one provided by RSpec::OpenAPI.description_builder method.

Inheritance of openapi: metadata

openapi: 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:

rb
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
end

The 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.

Selecting which request to document (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:

rb
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
  • Each {param} placeholder matches a single path segment independently, so multi-segment templates such as 'DELETE /orgs/{org_id}/members/{user_id}' work as expected.
  • When several requests match the pattern, the last one wins.
  • It works for both Rails (ActionDispatch::IntegrationTest) and Rack::Test-based specs (e.g. Roda, Hanami).
  • If the pattern can't be parsed, or no request issued in the example matches it, generation fails fast with a message listing the requests that were actually recorded.

Enum Support

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:

rb
it 'returns user status', openapi: {
  enum: {
    'status' => %w[active inactive suspended],
  },
} do
  get '/users/1'
  expect(response.status).to eq(200)
end

This generates:

yaml
schema:
  type: object
  properties:
    status:
      type: string
      enum:
        - active
        - inactive
        - suspended

Nested Paths

For nested objects, use dot notation to specify the path:

rb
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)
end

Array Items

For properties inside array items, use the array property name followed by the item property:

rb
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)
end

Request vs Response Enums

By 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:

rb
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)
end

Dynamic-key Object Support (additionalProperties)

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.

rb
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)
end

This generates:

yaml
schema:

Issues· 6 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyopenapirailsrspecruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类后端框架
定价开源

> 相关工具

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架