Blog

Testing with Rails 3.1 authentication

Creating an authentication system from scratch is simple with Rails 3.1, thanks to these two RailsCasts. What's left unexplained, however, is how to take advantage of this in your controller and model tests.

In order to test methods that require an authenticated user, you have to be able to create and maintain a session. We do that by setting a user's auth_token as a cookie in the browser, and then checking it against the stored token with Rails. But a browser isn't part of the equation in model and controller tests, so writing something like the following won't help you create a session:

In order for cookies[:auth_token] to be available in your app/ code, you have to attach it to @request, one of three special instance variables in an ActionController spec. So, the line becomes:

Then you're good! Your session now behaves like it normally should.