binarylogic/authlogic — Issue #287: Weird timing issue in loading current_user / session
Author: DaveSanders
Created: 2011-10-28 03:59:54+00:00
State: open

This is a very specific issue, so bear with me.

I have a relatively simple new app, using Authlogic / Declarative Auth. Rails 3.1.1.

I'm testing it with rspec + capybara + selenium, all latest versions.

I have a request spec that logs the user in, hits a page, submits a form via AJAX then checks to see if a div loaded with the result. The page started erroring when I was testing it and it came down to my current_user being nil. Current_user is being loaded in my application controller like so:

filter_access_to :all
helper_method :current_session, :current_user
before_filter {|c| Authorization.current_user = c.current_user; @page_data={}}

def current_session
return @current_session if defined?(@current_session)
@current_session = UserSession.find
end

def current_user
return @current_user if defined?(@current_user)
@current_user = current_session && current_session.user
end

Now the weird part. If I set my Capybara.default_wait_time to at least 5 seconds, current_user is there and works. If I set it to 4 seconds or less, it fails. This timing makes the test harness wait that many seconds on the AJAX call and then the controller code fires up. If I set a debugger at the entry to my erroring action, I can do a "p current_user" and if its > 5 seconds, it comes up every time.

At <5 seconds current_user is nil. request.cookies does have stuff in there, like the session and user credentials. UserSession.find comes back nil as well.

This makes no sense to me. If the controller has the process and the cookies are all there, why wouldn't invoking UserSession.find come back with the user?

Maddening. Most of my site is behind authentication and I don't want to base all of my tests on the crapshoot of guessing the right number of seconds. I gotta be missing something.