DRYing your tests with shared_examples

Reducing lines of code in your tests that share common behaviour.

Posted by Ricardo Trindade on January 26, 2019

It is likely that you have an authentication layer behind your Rails' controllers, for example some actions are only available for logged in users. For this example let's suppose you let authenticated users create likes and comments on the app.

A simple form of authentication could be to pass a token on the request headers as shown below. There are other options for authentication but we'll keep it simple for now.

Then the controllers would extend from this base controller, inehriting the authentication part.

Using Shared Examples on Rspec

Now you when writing tests for these controllers, you should test the authentication layer. For this I like to use rspec shared_examples where you can reuse the same tests through several spec files. However, when using you have to be disciplined and keep the same name for your variables. In the examples below call_action is the controller action.

All the tests in the shared_examples test all possible scenarios regarding authenticated requests. I personally like to place these files under spec/support. To load these files you can add this to your rails_helper:

So on your controller spec files you would only need to call it_behaves_like and use the name you defined on the shared_examples file.

It is not mandatory to keep the shared_examples in separate files, you can declare them directly on the spec_file. I just place them on the support directory because I am reusing it through several controller spec files.