rspec_api_documentation

rspec_api_documentation

Rails API文档自动生成工具

rspec_api_documentation是一款基于RSpec测试用例自动生成Rails API文档的开源工具。它支持HTML、JSON、Markdown等多种输出格式,可帮助开发者高效创建结构化的API文档。该工具提供丰富的配置选项,允许用户灵活定制文档生成流程,有助于提升API的可用性和可维护性。

RSpecAPI文档Ruby测试OpenAPIGithub开源项目

Code Climate Inline docs Gem Version

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

Gemfile

gem 'raddocs'

or 

gem 'apitome'

spec/spec_helper.rb

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

# spec/acceptance/orders_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Orders' do explanation "Orders resource" header "Content-Type", "application/json" get '/orders' do # This is manual way to describe complex parameters parameter :one_level_array, type: :array, items: {type: :string, enum: ['string1', 'string2']}, default: ['string1'] parameter :two_level_array, type: :array, items: {type: :array, items: {type: :string}} let(:one_level_array) { ['string1', 'string2'] } let(:two_level_array) { [['123', '234'], ['111']] } # This is automatic way # It's possible because we extract parameters definitions from the values parameter :one_level_arr, with_example: true parameter :two_level_arr, with_example: true let(:one_level_arr) { ['value1', 'value2'] } let(:two_level_arr) { [[5.1, 3.0], [1.0, 4.5]] } context '200' do example_request 'Getting a list of orders' do expect(status).to eq(200) end end end put '/orders/:id' do with_options scope: :data, with_example: true do parameter :name, 'The order name', required: true parameter :amount parameter :description, 'The order description' end context "200" do let(:id) { 1 } example 'Update an order' do request = { data: { name: 'order', amount: 1, description: 'fast order' } } # It's also possible to extract types of parameters when you pass data through `do_request` method. do_request(request) expected_response = { data: { name: 'order', amount: 1, description: 'fast order' } } expect(status).to eq(200) expect(response_body).to eq(expected_response) end end context "400" do let(:id) { "a" } example_request 'Invalid request' do expect(status).to eq(400) end end context "404" do let(:id) { 0 } example_request 'Order is not found' do expect(status).to eq(404) end end end end

Configuration options

# Values listed are the default values RspecApiDocumentation.configure do |config| # Set the application that Rack::Test uses config.app = Rails.application # Used to provide a configuration for the specification (supported only by 'open_api' format for now) config.configurations_dir = Rails.root.join("doc", "configurations", "api") # Output folder # **WARNING*** All contents of the configured directory will be cleared, use a dedicated directory. config.docs_dir = Rails.root.join("doc", "api") # An array of output format(s). # Possible values are :json, :html, :combined_text, :combined_json, # :json_iodocs, :textile, :markdown, :append_json, :slate, # :api_blueprint, :open_api config.format = [:html] # Location of templates config.template_path = "inside of the gem" # Filter by example document type config.filter = :all # Filter by example document type config.exclusion_filter = nil # Used when adding a cURL output to the docs config.curl_host = nil # Used when adding a cURL output to the docs # Allows you to filter out headers that are not needed in the cURL request, # such as "Host" and "Cookie". Set as an array. config.curl_headers_to_filter = nil # By default, when these settings are nil, all headers are shown, # which is sometimes too chatty. Setting the parameters to an # array of headers will render *only* those headers. config.request_headers_to_include = nil config.response_headers_to_include = nil # By default examples and resources are ordered by description. Set to true keep # the source order. config.keep_source_order = false # Change the name of the API on index pages config.api_name = "API Documentation" # Change the description of the API on index pages config.api_explanation = "API Description" # Redefine what method the DSL thinks is the client # This is useful if you need to `let` your own client, most likely a model. config.client_method = :client # Change the IODocs writer protocol config.io_docs_protocol = "http" # You can define documentation groups as well. A group allows you generate multiple # sets of documentation. config.define_group :public do |config| # By default the group's doc_dir is a subfolder under the parent group, based # on the group's name. # **WARNING*** All contents of the configured directory will be cleared, use a dedicated directory. config.docs_dir = Rails.root.join("doc", "api", "public") # Change the filter to only include :public examples config.filter = :public end # Change how the post body is formatted by default, you can still override by `raw_post` # Can be :json, :xml, or a proc that will be passed the params config.request_body_formatter = Proc.new { |params| params } # Change how the response body is formatted by default # Is proc that will be called with the response_content_type & response_body # by default, a response body that is likely to be binary is replaced with the string # "[binary data]" regardless of the media type. Otherwise, a response_content_type of `application/json` is pretty formatted. config.response_body_formatter = Proc.new { |response_content_type, response_body| response_body } # Change the embedded style for HTML output. This file will not be processed by # RspecApiDocumentation and should be plain CSS. config.html_embedded_css_file = nil # Removes the DSL method `status`, this is required if you have a parameter named status # In this case you can assert response status with `expect(response_status).to eq 200` config.disable_dsl_status! # Removes the DSL method `method`, this is required if you have a parameter named method config.disable_dsl_method! end

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.

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:

ENV["DOC_FORMAT"] ||= "json" RspecApiDocumentation.configure do |config| config.format = ENV["DOC_FORMAT"] end
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.

    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

swagger: '2.0' info: title: OpenAPI App description: This is a sample server. termsOfService: 'http://open-api.io/terms/' contact: name: API Support url: 'http://www.open-api.io/support' email: support@open-api.io license: name: Apache 2.0 url: 'http://www.apache.org/licenses/LICENSE-2.0.html' version: 1.0.0 host: 'localhost:3000' schemes: - http - https consumes: - application/json - application/xml produces: - application/json - application/xml paths: /orders: hide: true /instructions: hide: false get: description: This description came from configuration file hide: true

Example of spec file with :open_api format

resource 'Orders' do explanation "Orders resource" authentication :apiKey, :api_key, description: 'Private key for API access', name: 'HEADER_KEY' header "Content-Type", "application/json" let(:api_key) { generate_api_key } get '/orders' do route_summary "This URL allows users to interact with all orders." route_description "Long description." # This is manual way to describe complex parameters parameter :one_level_array, type: :array, items: {type: :string, enum: ['string1', 'string2']}, default: ['string1'] parameter :two_level_array, type: :array, items: {type: :array, items: {type: :string}} let(:one_level_array) { ['string1', 'string2'] } let(:two_level_array) { [['123', '234'], ['111']] } # This is automatic way # It's possible because we extract parameters definitions from the values parameter :one_level_arr, with_example: true parameter :two_level_arr, with_example: true let(:one_level_arr) { ['value1', 'value2'] } let(:two_level_arr) { [[5.1, 3.0], [1.0, 4.5]] } context '200' do example_request 'Getting a list of orders' do expect(status).to eq(200) expect(response_body).to eq(<response>) end end end put '/orders/:id' do route_summary "This is used to update orders." with_options scope: :data, with_example: true do parameter :name, 'The order name', required: true parameter :amount parameter :description, 'The order description' end context "200" do let(:id) { 1 } example 'Update an order' do request = { data: { name: 'order', amount: 1, description: 'fast order' } } # It's also possible to extract types of parameters when you pass data through `do_request` method. do_request(request) expected_response = { data: { name: 'order', amount: 1, description: 'fast order' } } expect(status).to eq(200) expect(response_body).to eq(<response>) end end context "400"

编辑推荐精选

蛙蛙写作

蛙蛙写作

AI小说写作助手,一站式润色、改写、扩写

蛙蛙写作—国内先进的AI写作平台,涵盖小说、学术、社交媒体等多场景。提供续写、改写、润色等功能,助力创作者高效优化写作流程。界面简洁,功能全面,适合各类写作者提升内容品质和工作效率。

AI辅助写作AI工具蛙蛙写作AI写作工具学术助手办公助手营销助手AI助手
Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

下拉加载更多