Wednesday, January 16, 2008

Cool way to test controllers that are protected by an authentication system

Whenever you've got a Rails app that has a login system, you tend to run into problems testing your controllers because the before_filter :login_required (or whatever you've called it) fires before you get to any of the controller logic you want to test.

So you typically end up adding stuff to your tests to fake out the login tests ... either by manually creating a session that will pass the before_filter or by actually including code to do a valid login in the setup (before) for the test.

I just came across a blog post:
Using Rspec On Controllers that points out that you can very simply avoid this problem by stubbing out the method being called by the before_filter:


controller.stub!(:myfilter).and_return(true)


Sweet!

-Steve