Director of Cloud Engineering @ Team8Solutions, Freelancer
Generate API Documentation Using Rspec Acceptance Tests
Step 1:
Install required gems
12
gem'rspec_api_documentation'gem'raddocs'
Step 2:
Create acceptance_helper.rb in spec folder
acceptance_helper.rb
12345678910111213
require'rails_helper'require'rspec_api_documentation'require'rspec_api_documentation/dsl'RspecApiDocumentation.configuredo|config|config.format=:jsonconfig.curl_host='http://fysquare.dev'# Will be used in curl requestconfig.api_name="FySquare API"# Your API nameconfig.request_headers_to_include=["Host","Content-Type"]config.response_headers_to_include=["Host","Content-Type"]config.curl_headers_to_filter=["Authorization"]# Remove this if you want to show Auth headers in requestconfig.keep_source_order=trueend
Create raddoc.rb in initializers
raddoc.rb
123
Raddocs.configuredo|config|config.api_name="FySquare API Documentation"end
Add API route in config.rb
routes.rb
12
mountRaddocs::App=>"/api_docs"end
Step 3:
Now you need to write acceptance specs which will be used to generate docs.
Below is the spec for listing users API. You can change the params depends on your API.
require'acceptance_helper'resource"User",acceptance:truedolet(:user){FactoryGirl.create(:user)}beforedoheader'Authorization','Auth code'header'Content-Type','application/json'endget"/api/users"doexample_request"Listing Users"doexplanation"List all the users in the system"expect(status).toeq200endparameter:ids,"List of user ids to be fetched"parameter:email,"Search users by email"parameter:page,"Page to view"example"Get users by params"doexplanation"Get users by params"do_request(:ids=>[user.id])expect(status).toeq200do_request(:email=>['foo@example.com','doo@example.com'])expect(status).toeq200endendget"/api/users/:id"dolet(:id){user.id}example_request"Getting a specific user"doexpect(status).toeq(200)endendend