Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set session variables in Rails integration tests

In Rails integration tests, how do I set a session variable (:user_id in my case)?

Obviously it's not a full integration test then, but given that in my app user authentication cannot happen without manual user interaction, can i somehow work around and have a session variable set manually?

Have tried the following: "session" is not available in that scope, open_session returns a session which I did not find a way to update.

like image 762
jbasko Avatar asked Sep 12 '11 21:09

jbasko


2 Answers

As far as I can tell, you can't. The session value in integration tests (in rails 3.2.2) is a copy. (Rails gods: Please correct me if I'm wrong.) You can set the value, but it won't affect the next get/post because it's a local copy of the real session. Great for assert tests, not so great for keeping state in session during the integration test.

I have a test controller to support my JavaScript testing via Evergreen.

My solution was to add a method to my test controller and a route available when I'm NOT in production, that allows me to set session values.

Basically my app_test#set_session method screens the parameter names for a prefix, if the prefix is found, then the value of session for the prefix stripped parameter name is set. Something like:

    params.each() do |key, value|
            next if ( key !~ /^set_session_/)
            session[ key.slice( ("set_session_".size())..-1).to_sym ] = value
    end
    # don't forget to render something/anything

So, to set session variables during my integration tests, I have a small chunk of code like:

    prefix = "set_session_"
    post( "/set_session.html", { (prefix + "user_id") => "My Name Is Mudd" } )

Not as pretty as "session[ :user_id ] = 'My Name Is Mudd'", but it works. My next post/get will see session[ :user_id ] set with the desired value.

This is easily extended to pass integers, symbols, etc, and of course, multiple session key/value pairs can be set at once. Not pretty, but not bad.

like image 151
eclectic923 Avatar answered Oct 16 '22 18:10

eclectic923


Why can authentication not happen without manual interaction? Does it use a CAPTCHA? If so, stub that part out for running in a test environment.

like image 39
Andy Waite Avatar answered Oct 16 '22 20:10

Andy Waite