I have been writing a lot of tests for our API lately, and I wanted to share a technique that has helped me build a test suite that is easy to understand and write. Our API keeps a pretty consistent pattern which makes it a perfect candidate for RSpec shared examples. Similar to RSpec shared context which I discussed in another post, shared examples are a great way to clean up test code and create useful abstractions.
To include a shared example in a spec you have to use one of the following methods:
1 2 3 4 |
|
These methods allow you to pass parameters that can be used in the example group. I utilize this for my api tests to provide a factory name, the path for the request and the model:
1 2 3 4 5 6 7 8 9 |
|
In a Rails project, it is usually recommended to include shared examples under the support folder, so that they are autoloaded and available to use in all your tests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Now when I want to test another API endpoint that follows the RESTful index pattern, I can reuse this spec. Another benefit is that if I were to change the behavior for the index action by requiring an oauth token, I would only need to make the change in one place. Shared examples are also composable, so you could create a shared example for a restful resource by combining shared examples for all the different route types:
1 2 3 4 5 6 7 |
|