8

I started writing functional tests for my rails app today. I use the RESTful authentication plugin. I ran into a couple confusing things I hope someone can clarify for me.

1) I wrote a quick login function because most of the functions in my rails app require authentication.

def login_as(user)
   @request.session[:user_id] = user ? user.id : nil
end

The issue I see with this function, is it basically fakes authentication. Should I be worried about this? Maybe it is okay to go this route as long as I test the true authentication method somewhere. Or maybe this is terrible practice.

2) The second confusing thing is that in some places in my functional tests, I need the full authentication process to happen. When a user is activated, I have the do_activate method create some initial objects for the user. It is analogous to the creation of a blank notebook object and pen object for a student application, if that makes sense.

So in order to properly test my application, I need the user to hit that activation state so those objects are created. I am currently using Factory Girl to create the user, and then calling the login_as function above to fake authentication.

I guess another option would be to skip the full authentication sequence and just create the blank objects with Factory Girl. I could test the proper authentication somewhere else.

What do you think? If I should go through the proper sequence, why isn't the code below invoking the do_activate function?

user = Factory.create(:user)
user.active = 1
user.save

Thank you!

Tony
  • 18,776
  • 31
  • 129
  • 193
  • [Here is a similar question I asked](http://stackoverflow.com/questions/64827/rails-restful-authentication-rspec-how-to-test-new-models-that-require-authen) and a bunch of links I pulled together. – srboisvert May 15 '09 at 08:43

1 Answers1

7

Faking it is perfectly acceptable.

However, write other tests that ensure that the things you want protected are protected. So

test "it should show the profile page" do
  user = Factory(:user)
  login_as(user)
  get :show, :id => user
  assert_response :success
end

test "it should not show the profile page cos I'm not logged in" do
  user = Factory(:user)
  get :show, :id => user
  assert_response :redirect
end

Feel free to hit me up for followups!

Brian Hogan
  • 3,033
  • 21
  • 18