How to set session variables in Rails integration tests

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

Obviously, this is not a complete integration test, but considering that in my application user authentication cannot happen without manual interaction with the user, can I somehow get around and set the session variable manually?

We tried the following: "session" is not available in this area, open_session returns a session that did not find a way to update.

+7
source share
2 answers

As far as I can tell, you cannot. The value of the session in the integration tests (in rails 3.2.2) is a copy. (Rare gods: Please correct me if I'm wrong.) You can set the value, but this will not affect the next get / post because it is a local copy of the real session. Great for affirmative tests, not so good for maintaining state during an integration test.

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

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

Basically, my app_test # set_session method escapes the parameter names for the prefix, if the prefix is ​​found, then the session value for the stripped parameter name prefix 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 the session variables during my integration tests, I have a small piece 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 message / receipt will show that the session [: user_id] is set to the right value.

It is easily distributed to transmit integers, characters, etc., and, of course, several session key / value pairs can be set at the same time. Not beautiful, but not bad.

+5
source

Why authentication is not possible without manual interaction? Does he use CAPTCHA? If so, then stubs that go beyond working in a test environment.

+1
source

All Articles