27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

148 CHAPTER 7 Basic access control<br />

7.4 Namespace routing<br />

Although it’s fine and dandy to ensure that admin users can get to special places in<br />

your application, you haven’t yet added the functionality for triggering whether or not<br />

a user is an admin from within the application itself. To do so, you create a new<br />

namespaced section of your site called admin. The purpose of namespacing in this case<br />

is to separate a controller from the main area of the site so you can ensure that users<br />

accessing this particular controller (and any future controllers you create in this<br />

namespace) have the admin field set to true.<br />

You begin by generating a namespaced controller with an empty index action by<br />

using this command:<br />

rails g controller admin/users index<br />

When the / separator is used between parts of the controller, Rails knows to generate<br />

a namespaced controller called Admin::UsersController at app/controllers/admin/<br />

users_controller.rb. The views for this controller are at app/views/admin/users, and<br />

the spec is at spec/controllers/admin/users_controller_spec.rb.<br />

This command also inserts a new route into your config/routes.rb file. You don’t<br />

want that, so remove this line:<br />

get "users/index"<br />

Now you must write a spec for this newly generated controller to ensure only users<br />

with the admin attribute set to true can access it. Open spec/controllers/admin/<br />

users_controller_spec.rb and write an example to ensure non-signed-in users can’t<br />

access the index action, as shown in the following listing.<br />

Listing 7.16 spec/controllers/admin/users_controller_spec.rb<br />

require 'spec_helper'<br />

describe Admin::UsersController do<br />

let(:user) do<br />

user = Factory(:user)<br />

user.confirm!<br />

user<br />

end<br />

context "standard users" do<br />

before do<br />

sign_in(:user, user)<br />

end<br />

it "are not able to access the index action" do<br />

get 'index'<br />

response.should redirect_to(root_path)<br />

flash[:alert].should eql("You must be an admin to do that.")<br />

end<br />

end<br />

end

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!