Problems to test controllers which require login


#1

Hi there,

I have a quite stupid problem with my testing environment. I’m trying to
test my controllers but every controller with a login rewuirement will
fail (because there is no logged in user in the session). I realized the
conceptual problem behind this, but I’m not able to solve it.

What I have done so far:

  • Login in the test class as described in the Agile Rails Book. This
    works perfect for the LoginControllerTest (even for sites, that need
    logged in users).

  • Extracted the login functionallity in the test_helper.rb file (again
    as described in the book). But unfortunatly this works only for the
    LoginControllerTest. In every other Controller test I got an error while
    performing this method. (I tried this with the original sources from the
    book, and it doesn’t worked, too).

  • The last thing I’ve tried was to send the session information every
    time I request a controller action that requires an authorized user (I
    know this is ugly but was my last hope). My code looks something like
    this:

    get :index, :session => {:user => User.find(1)}
    

Again this doesn’t worked out.

Now this list is all I can ask for help. If anybody could help me out
with this problem.

thanks a lot.

cheers

Dirk


#2

Just throw this in your test’s setup method

def setup

@session = @request.session
@session[:user] = users(:first)
end

Pat


#3

Thanks for the fast response Pat. Your adivce works perfectly!

Thanks a lot

Dirk


#4

get and post take up to 3 arguments:

action, parameters = nil, session = nil, flash = nil

so

get :action_that_requires_login, {}, { :user_id => 1 }

will get the page, with no parameters, and a session where session
[:user_id] == 1

This allow a lot more flexibility in testing…for instance testing
what happens
if a user that isn’t logged in tries to access an action.


– Tom M.


#5

I’m using the salted login generator with happyness, exept now I’d
like to test my controllers behind the salted login. I’ve read on the
mailing list about this issue, and I’ve used the
pass_the_session_to_the_action but without success.

This is a line of the controller tested, I’m passing a param
(level_id) and then I pass the user session as in the salted login
generator tests
get :show_level, {:level_id => 1 }, { :user => @bob }
it gets redirected to the userController… so… this is definitly
bad I think it means the before_filter hasn’t recognized me.
@bob is coming from the :users fixture correctly included in the
current test suite.

?

Thanks,
Enrico


“The only thing necessary for the triumph of evil
is for good men to do nothing”
Edmund Burke