Document your Rails API by Writing Acceptance Specs

So you have been working on a Rails API, and now you need to create a browsable HTML documentation for it. One popular approach is to generate the docs from comments in the code. The problem with this is that comments are often not updated together with the code, and the documentation quickly becomes outdated. Recently I have started using an interesting alternative: Rspec Api Documentation.

It’s a gem that allows you to generate API docs from acceptance specs. So instead of writing comments, you write an actual test code. So the chances that your documentation reflects the actual API are higher. And in terms of methodology, writing specs as part of any code change is something we do anyway, so it’s a win-win.

Here is how the spec looks like:

resource "ProviderConnection" do
  let!(:org) { create(:organization) }
  let!(:provider) { create(:provider, organizations: [ org ]) }
  let!(:consumer) { create(:consumer, organizations: [ org ]) }
  let!(:connection) { create(:provider_connection, 
                       consumer: consumer, provider: provider) }

  before do
    login_as consumer

  header "Accept", "application/vnd.api+json"
  header "Content-Type", "application/vnd.api+json"

  get "/v1/provider_connections/:id" do
    response_field :connection_status, "Status of the connection. Possible values: 'connected' / 'disconnected' "

    let!(:id) { }
    example_request "Get a detailed information about a provider connection" do
      expect(status).to eq 200
      expect(response_body).to include_json(...)

As you can see, the syntax is pretty simple. A few points about it:

  • resource groups together all the examples for the same resource.
  • You can have several example requests for the same resource action, highlighting a different aspect of the request in each example.
  • In addition to GET, all the usual HTTP verbs are supported
  • When the request URL contains a variable (using the usual routes :id syntax), you have to define it using let!

You can choose between several types of output formats and several types of view renderers. Choosing Raddocs viewer, this is how your eventual docs page would look like for the ProviderConnection resource:


That’s it for this short introduction of Rspec Api Documentation.

Leave a Reply

Your email address will not be published. Required fields are marked *