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!