Authentication Best Practice – Merb or Rails
IRC seems to be full of requests for authentication and best practices. After much discussion being repeated, I felt it was best to post it somewhere that I can link to.
Testing authentication is by no means a best practice, however most implement this in the most non-DRY way. The most common line being:
[sourcecode language="ruby"]@response.status.should == 401[/sourcecode]
I think this is great, however that allows for two big mistakes. If you forget to test a single controller method with this statement, you have no guarantee that this action is hidden behind authentication. The chances of this are increased for each method you write because chances for human error increases each time. This is why I am an advocate of another practice.
Open up your framework’s (Merb, Rails, or whatever) Application Controller and insert
[sourcecode language="ruby"]before :ensure_authenticated[/sourcecode]
Then open up a test file and test that the before filter is being hit. There you go! You just tested authentication once and for all. Now when you want to make an action visible to the public, use a skip_before call.
[sourcecode language="ruby"]skip_before :ensure_authenticated,
nly => [:index][/sourcecode]
And write the single test to ensure your not receiving a 401 error when not logged in. This removes writing login_user all over in your tests. Just place it once inside of a before(:each) block and logout in the few tests where that is necessary.
Enjoy your dried up, shriveled tests!

