Home

How to do rails tests when running with restful_authentication

Posted by Simon on May 26, 2009 at 01:18 AM

Categories: code, rails, ruby

The Restful Authentication plugin seems to be the standard right now, although I'm staring to wish I'd tried something else, maybe AuthLogic... because restful_authentication is kind of poorly documented. One serious error of ommission is how the hell do you update your tests so that you can run them on controllers that require a logged in user? Well, I have had the pain, and so you can have the quick answer, here it is.

Assuming you are using ActionController::TestCase ... first edit test_helper.rb:

  # Add this helper function to test_helper.rb
# It will allow you to run any block under the aegis of
# a controller of your choosing. This is not something
# that is possibly by default
def run_with_controller( controller_class )
old_controller = @controller
@controller = controller_class.new
yield
@controller = old_controller
end

Now you can use that helper method in your test cases, in the setup function do this:

  def setup
run_with_controller(SessionsController) do
post :create, { :login => "george", :password => "monkey" }
end
end

What you're doing here is simply making a POST to the Restful Authentication SessionsController to "create" a new session, pass in a login/password that exists in your fixtures. And that's it.

By the way, if you chose to install with RSpec because of the dire warnings that old fashioned tests will be out of date, but aren't currently using RSpec for you other tests, you should copy the rspec fixture data into test/ so that you get the right password hashes. Tricky...

Comments

There are 3 comments on this post. Post yours →

I started doing this then I realized I already had started using an easier alternative.

Before post actions just update the user in the session

@request.session[:user_id] = users(:quentin).id

On gets you can specify the session

get :show, {:id => 1}, { :user_id => users(:quentin).id }

restful_authentication should have a wiki we can contribute to.. actually i think it does. I'll look into that when I have some free time. :-)

Thanks for sharing I was banging my head against this one too.

Post a comment

Required fields in bold.

 

Browse Old Articles

Categories:

Popular posts:

Subscribe to:

Blogroll: