Testing Visitors in Devise with RSpec


We’re hot and heavy in the middle of Rails Rumble, and I’m taking a break to publish a problem I just had with the new Devise authentication engine. I love it so far, by the way, but I ran into a problem when I started testing for *authorization*. Authentication – verifying that a user is who they say they are – went just fine. Authorization – verifying that an authenticated user has access to a certain resource – is where I ran into trouble. Devise tries to make it easy to test as a certain member:

# spec/controllers/profiles_controller_spec.rb
require 'spec_helper'

include Devise::TestHelpers

describe ProfilesController do
  describe "as a member" do
    before do
      @member = Factory.create :user
      sign_in @member
    end

    ...
  end
end

I can sign in as a certain user, and test that things work okay. But what if I want to test as a visitor, not logged in? I want to verify that the visitor is redirect to the sign_in page when they try to access a members-only resource. It sounds easy – just don’t sign in, right? This gives this error:

undefined method `authenticate!' for nil:NilClass

That’s because it’s trying to authenticate, and it’s missing something behind the scenes in Deviseland. But we can trick Devise (or fix it, whatever) by signing out. So:

# spec/controllers/profiles_controller_spec.rb
require 'spec_helper'

include Devise::TestHelpers

describe ProfilesController do
  describe "as a member" do
    before do
      sign_out :user
    end

    ...
  end
end

I hope this helps others, whether you’re under a Rumble-esque time crunch or not!

Advertisements

Tags: , , , ,

2 Responses to “Testing Visitors in Devise with RSpec”

  1. Tom Says:

    The devise readme actually explains how to fix this: https://github.com/plataformatec/devise


    If you’re using RSpec and want the helpers automatically included within all describe blocks, add a file called spec/support/devise.rb with the following contents:

    RSpec.configure do |config|
    config.include Devise::TestHelpers, :type => :controller
    end

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: