Testing a Rails API with RSpec and Devise
Recently I was trying to build a simple API endpoint for a rails app. I was trying to use jquery-tokeninput to create a form field for a model that was using acts-as-taggable-on. To handle the autocomplete, I felt like it would be cleaner to set up a new controller action that had a single purpose: handle JSON requests for a list of tags. So, I created my api/tags_controller.rb and added the code to find the relevant tags and installed the jquery-tokeninput plugin.
Everything worked great until I decided I should write some tests for the API endpoint. I found some articles online recommending request specs for testing API’s, which seemed to make a lot of sense. Straightforward, right? I just need to write a spec that hits the API endpoint and make sure it gets back the tags I expect in the JSON response.
Get David Van Der Beek’s stories in your inbox
Join Medium for free to get updates from this writer.
I wrote my test and…it failed. Instead of a successful response, I was being redirected. Devise wanted a user to be signed in. So I searched StackOverflow and blogs across the internet. Most of them told me to set up a support file with a login function. Something like this:
The blog post and stack overflow both warned me that this was outdated, but there were no clear instructions on the correct way to handle this problem, so I tried it anyway…to no avail.
Finally, I managed to find the information I needed on the devise wiki. The article sounds like it’s talking about feature specs since it includes “Capybara” in the title, but this does work in my request specs:
Simple, but surprisingly hard to find information!





