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

rspec_api_documentation

> 编程语言
开源

自动从 RSpec 生成 API 文档

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

工具介绍

自动从 RSpec 生成 API 文档

RSpec API Doc Generator

Generate pretty API docs for your Rails APIs.

Check out a sample.

Changes

Please see the wiki for latest changes.

Installation

Add rspec_api_documentation to your Gemfile

gem 'rspec_api_documentation'

Bundle it!

$ bundle install

Set up specs.

$ mkdir spec/acceptance
$ vim spec/acceptance/orders_spec.rb
ruby
require 'rails_helper'
require 'rspec_api_documentation/dsl'

resource "Orders" do
  get "/orders" do
    example "Listing orders" do
      do_request

      expect(status).to eq 200
    end
  end
end

Generate the docs!

$ rake docs:generate
$ open doc/api/index.html

Viewers

Consider adding a viewer to enhance the generated documentation. By itself rspec_api_documentation will generate very simple HTML. All viewers use the generated JSON.

  • Raddocs - Sinatra app
  • Apitome - Rails engine

Gemfile

gem 'raddocs'

or 

gem 'apitome'

spec/spec_helper.rb

ruby
RspecApiDocumentation.configure do |config|
  config.format = :json
end

For both raddocs and apitome, start rails server. Then

open http://localhost:3000/docs for raddocs

or

http://localhost:3000/api/docs for apitome

Sample App

See the example folder for a sample Rails app that has been documented. The sample app demonstrates the :open_api format.

Example of spec file

…

Configuration options

…

Format

  • json: Generates an index file and example files in JSON.
  • html: Generates an index file and example files in HTML.
  • combined_text: Generates a single file for each resource. Used by Raddocs for command line docs.
  • combined_json: Generates a single file for all examples.
  • json_iodocs: Generates I/O Docs style documentation.
  • textile: Generates an index file and example files in Textile.
  • markdown: Generates an index file and example files in Markdown.
  • api_blueprint: Generates an index file and example files in APIBlueprint.
  • append_json: Lets you selectively run specs without destroying current documentation. See section below.
  • slate: Builds markdown files that can be used with Slate, a beautiful static documentation builder.
  • open_api: Generates OpenAPI Specification (OAS) (Current supported version is 2.0). Can be used for Swagger-UI

append_json

This format cannot be run with other formats as they will delete the entire documentation folder upon each run. This format appends new examples to the index file, and writes all run examples in the correct folder.

Below is a rake task that allows this format to be used easily.

ruby
RSpec::Core::RakeTask.new('docs:generate:append', :spec_file) do |t, task_args|
  if spec_file = task_args[:spec_file]
    ENV["DOC_FORMAT"] = "append_json"
  end
  t.pattern    = spec_file || 'spec/acceptance/**/*_spec.rb'
  t.rspec_opts = ["--format RspecApiDocumentation::ApiFormatter"]
end

And in your spec/spec_helper.rb:

ruby
ENV["DOC_FORMAT"] ||= "json"

RspecApiDocumentation.configure do |config|
  config.format    = ENV["DOC_FORMAT"]
end
bash
rake docs:generate:append[spec/acceptance/orders_spec.rb]

This will update the current index's examples to include any in the orders_spec.rb file. Any examples inside will be rewritten.

api_blueprint

This format (APIB) has additional functions:

  • route: APIB groups URLs together and then below them are HTTP verbs.

    ruby
    route "/orders", "Orders Collection" do
      get "Returns all orders" do
        # ...
      end
    
      delete "Deletes all orders" do
        # ...
      end
    end

    If you don't use route, then param in get(param) should be an URL as states in the rest of this documentation.

  • attribute: APIB has attributes besides parameters. Use attributes exactly like you'd use parameter (see documentation below).

open_api

This format (OAS) has additional functions:

  • authentication(type, value, opts = {}) (Security schema object)

    The values will be passed through header of the request. Option name has to be provided for apiKey.

    • authentication :basic, 'Basic Key'
    • authentication :apiKey, 'Api Key', name: 'API_AUTH', description: 'Some description'

    You could pass Symbol as value. In this case you need to define a let with the same name.

    authentication :apiKey, :api_key
    let(:api_key) { some_value } 
  • route_summary(text) and route_description(text). (Operation object)

    These two simplest methods accept String. It will be used for route's summary and description.

  • Several new options on parameter helper.

    • with_example: true. This option will adjust your example of the parameter with the passed value.
    • example: <value>. Will provide a example value for the parameter.
    • default: <value>. Will provide a default value for the parameter.
    • minimum: <integer>. Will setup upper limit for your parameter.
    • maximum: <integer>. Will setup lower limit for your parameter.
    • enum: [<value>, <value>, ..]. Will provide a pre-defined list of possible values for your parameter.
    • type: [:file, :array, :object, :boolean, :integer, :number, :string]. Will set a type for the parameter. Most of the type you don't need to provide this option manually. We extract types from values automatically.

You also can provide a configuration file in YAML or JSON format with some manual configs. The file should be placed in configurations_dir folder with the name open_api.yml or open_api.json. In this file you able to manually hide some endpoints/resources you want to hide from generated API specification but still want to test. It's also possible to pass almost everything to the specification builder manually.

Example of configuration file

…

Example of spec file with :open_api format

…

Filtering and Exclusion

rspec_api_documentation lets you determine which examples get outputted into the final documentation. All filtering is done via the :document metadata key. You tag examples with either a single symbol or an array of symbols. :document can also be false, which will make sure it does not get outputted.

…
ruby
# All documents will be generated into the top folder, :document => false
# examples will never be generated.
RspecApiDocumentation.configure do |config|
  # Exclude only document examples marked as 'private'
  config.define_group :non_private do |config|
    config.exclusion_filter = :private
  end

  # Only document examples marked as 'public'
  config.define_group :public do |config|
    config.filter = :public
  end

  # Only document examples marked as 'developer'
  config.define_group :developers do |config|
    config.filter = :developers
  end
end

DSL

Require the DSL

At the beginning of each acceptance/*_spec.rb file, make sure to require the following to pull in the DSL definitions:

ruby
require 'rspec_api_documentation/dsl'

Example Group Methods

resource

Create a set of documentation examples that go together. Acts as a describe block.

ruby
resource "Orders" do
end

get, head, post, put, delete, patch

The method that will be sent along with the url.

ruby
resource "Orders" do
  post "/orders" do
  end

  get "/orders" do
  end

  head "/orders" do
  end

  put "/orders/:id" do
    let(:id) { order.id }

    example "Get an order" do
      expect(path).to eq "/orders/1" # `:id` is replaced with the value of `id`
    end
  end

  delete "/orders/:id" do
  end

  patch "/orders/:id" do
  end
end

example

This is just RSpec's built in example method, we hook into the metadata surrounding it. it could also be used.

ruby
resource "Orders" do
  post "/orders" do
    example "Creating an order" do
      do_request
      # make assertions
    end
  end
end

example_request

The same as example, except it calls do_request as the first step. Only assertions are required in the block.

Similar to do_request you can pass in a hash as the last parameter that will be passed along to do_request as extra parameters. These will not become metadata like with example.

ruby
resource "Orders" do
  parameter :name, "Order name"

  post "/orders" do
    example_request "Creating an order", :name => "Other name" do
      # make assertions
    end
  end
end

explanation

This method takes a string representing a detailed explanation of the example.

ruby
resource "Orders" do
  post "/orders" do
    example "Creating an order" do
      explanation "This method creates a new order."
      do_request
      # make assertions
    end
  end
end

A resource can also have an explanation.

ruby
resource "Orders" do
  explanation "Orders are top-level business objects. They can be created by a POST request"
  post "/orders" do
    example "Creating an order" do
      explanation "This method creates a new order."
      do_request
      # make assertions
    end
  end
end

header

This method takes the header name and value. The value can be a string or a symbol. If it is a symbol it will send the symbol, allowing you to let header values.

ruby
resource "Orders" do
  header "Accept", "application/json"
  header "X-Custom", :custom_header

  let(:custom_header) { "dynamic" }

  get "/orders" do
    example_request "Headers" do
      expect(headers).to eq { "Accept" => "application/json", "X-Custom" => "dynamic" }
    end
  end
end

parameter

This method takes the parameter name, a description, and an optional hash of extra metadata that can be displayed in Raddocs as extra columns. If a method with the parameter name exists, e.g. a let, it will send the returned value up to the server as URL encoded data.

Special values:

  • :required => true Will display a red '*' to show it's required
  • :scope => :the_scope Will scope parameters in the hash, scoping can be nested. See example
  • :method => :method_name Will use specified method as a parameter value

Retrieving of parameter value goes through several steps:

  1. if method option is defined and test case responds to this method then this method is used;
  2. if test case responds to scoped method then this method is used;
  3. overwise unscoped method is used.
…

response_field

This method takes the response field name, a description, and an optional hash of extra metadata that can be displayed in Raddocs as extra columns.

Special values:

  • :scope => :the_scope Will scope the response field in the hash
ruby
resource "Orders" do
  response_field :page, "Current page"

  get "/orders" do
    example_request "Getting orders" do
      expect(response_body).to eq({ :page => 1 }.to_json)
    end
  end
end

You can also group metadata using with_options to factor out duplications.

ruby
resource "Orders" do
  post "/orders" do

    with_options :scope => :order, :required => true do
      parameter :name, "Order Name"
      parameter :item, "Order items"
    end

    with_options :scope =>

Issues· 108 开放

查看全部 Issues在 GitHub 打开

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

> 标签

Rubyapirspecruby

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

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言