views:

45

answers:

2

I use authlogic to authenticate users. In my controllers I use current_user, defined (as documented) as follows:

  def current_user_session
    return @current_user_session if defined?(@current_user_session)
    @current_user_session = UserSession.find
  end
  def current_user
    return @current_user if defined?(@current_user)
    @current_user = current_user_session && current_user_session.record
  end

I also use declarative_authorization to manage the current user's permissions. All works fine in the normal runtime scenario, but when I create functional tests that use request statements like " get_with", current_user in the controller is nil. I looked through the declarative_authorization test helper code and found that in this scenario, the declarative_authorization gem actually stores the current user in Authorization.current_user (which in turn comes from Thread.current["current_user"]). So there seems to be quite a mixup of how a current user is handled in different scenario's.

My question: what is the appropriate way of finding the current_user in both the normal runtime and the test scenario?

A: 

You can define a before_filter like this in application_controller.

before_filter { |c| Authorization.current_user = c.current_user }

Hitesh Manchanda
Yeah, I did try that. But that's the other way around: in functional test, Authorization.current_user contains the correct user, but c.current_user == nil. So this statement won't work...
Pascal Lindelauf
One question how are you maintaining your user session in the tests?Try to debug the session may be it's now persisting for some reason.
Hitesh Manchanda
As far as I'm concerned, to log in an user with authlogic you must create his session through UserSession.create(user(:admin)) and then the authlogic current user works.
Angelus
A: 

Angelus, you were right. I shouldn't be using get_with, post_with, etc. These just set the Authorization.current_user, session[:user] and session[:user_id] and these seem to be obsolete with authlogic. And for some reason, these even set UserSession to nil, which was causing the problem. So UserSession.create(users(:admin)), followed by a regular get, post, etc. is the way to go.

Pascal Lindelauf