3

I am trying to test my rails 3.1 app (I'm learning testing as I go) and I and stuck with how I authenticate a user since normally it sets a session but the tests aren't using the browser so session is an undefined method. I am using the new rails 3.1 has_secure password.

How can I correctly set up and test authentication, as well as test parts of the app that require the user to be authenticated?

My set up is as follows:

rspec 2 capybara guard factory_girl

Thank you!

Ben
  • 553
  • 1
  • 13
  • 25

1 Answers1

0

When you're doing a controller tests the sessions hash is the last parameter. Let's say you have something like this in your session controller tests:

post :create, :user => { :email => "blah@blah.com" }, :color => "red"

This sends through 2 params through to the controller: params[:user] and params[:color].

What about session variables ? Session variables are sent through as the last parameter. If we wanted to set a last_logged_in session variable, we would change the above to:

post :create, {:user => { :email => "blah@blah.com" }, :color => "red"}, {:last_logged_in => Time.now}

Notice the extra set up braces I put around the user and color parameters. Now you will have access to session[:last_logged_in] in your controller.

I highly recommend reading the ror guides. Here's one about controller testing: http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers

Luke Cowell
  • 703
  • 5
  • 14