We've been building an ecommerce application for an online bookstore. Now we've reached one of the most important stages in the application's design: building in the security to prevent malicious hackers from wreaking havoc. This four-part series shows you how to protect your application. This article is excerpted from chapter eight of the book Practical Rails Projects, written by Eldon Alameda (Apress; ISBN: 1590597818).
First, we want to test that when George tries to go to the admin section of the site, he gets redirected to the login page. Opentest/integration/authentication_test.rband create the DSL for our integration test, as shown in Listing 8-2.
Listing 8-2. First Version of the Authentication Integration Test
class AuthenticationTest < ActionController::IntegrationTest def test_successful_login george = enter_site(:george) george.tries_to_go_to_admin end
module BrowsingTestDSL include ERB::Util attr_writer :name
def tries_to_go_to_admin get "/admin/book/new" assert_response :redirect assert_redirected_to "/account/login" end
def enter_site(name) open_session do |session| session.extend(BrowsingTestDSL) session.name = name yield session if block_given? end end end
Here, the most interesting part is in thetries_to_go_to_adminmethod. This is where we test that the first part of the story goes as planned: George is redirected to the login page when trying to access admin pages. If you run the test, you get the following failure:
$ ruby test/integration/authentication_test.rb
--------------------------------------------Loaded suite test/integration/authentication_test Started F Finished in 1.44942 seconds.
1) Failure: test_successful_login(AuthenticationTest) [test/integration/ authentication_test.rb:17:in 'tries_to_go_to_admin' test/integration/ authentication_test.rb:6:in 'test_successful_login' /usr/local/lib/ruby/gems/1.8/gems/actionpack 1.12.1/lib/action_controller/integration.rb:427:in 'run']: Expected response to be a <:redirect>, but was <200>
1 tests, 1 assertions, 1 failures, 0 errors
It seems the redirection is not working, which should come as no surprise. Now itís time to put the authentication plugin to work.