Testing Authlogic with Factory Girl

rails rspec authlogic factory_girl

2009-10-23 17:02:51 +0000

There’s an interesting gotcha about testing Authlogic with factory_girl that I just ran into and spent a half hour trying to figure it out.

It’s a bug of the flesh (i.e. my fault), but it’s something that I’ve run into before, and I often forget about it whenever I write new specs.

Let’s say you have the code:

describe PoliciesController do
  before :each do
    activate_authlogic
   @user = Factory(:registered_user)
  end

  describe "POST create" do
    it 'should successfully create a policy if logged in' do
      UserSession.create @user
      # ... more stuff
    end

    # ERROR
    # ERROR
    # ERROR
    it 'should return an error if not logged in' do
      # test logged out code
    end
  end
end

The test for being logged out will not pass, even if the code is working correctly. The problem is, when you save a User (which is our acts_as_authentic class), it logs that user in automatically.

The problem with this is the examples for testing authlogic all show a call to UserSession.create with a fixture. This is fine, since the fixture is saved to the database behind authlogic’s back, but when we use factory_girl like in the above example, it creates and saves the User and all the hooks get called, which includes logging the user in.

So, in short, if you’re using factory_girl like I am above, don’t call UserSession.create

blog comments powered by Disqus