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:

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 *