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.

142 CHAPTER 7 Basic access control<br />

flash[:alert] = "You must be an admin to do that."<br />

redirect_to root_path<br />

end<br />

end<br />

This method uses the authenticate_user! method (provided by Devise) to ensure<br />

that the user is signed in. If the user isn’t signed in when this method is called, they’re<br />

asked to sign in. If the user isn’t an admin after signing in, they’re shown the “You<br />

must be an admin to do that” message and redirected to the homepage.<br />

To call this method, call before_filter at the top of your ProjectsController, as<br />

shown in the following listing.<br />

Listing 7.8 app/controllers/projects_controller.rb<br />

before_filter :authorize_admin!, :except => [:index, :show]<br />

With that in place, you can rerun the spec bin/rspec spec/controllers/projects<br />

_controller_spec.rb, which should now pass:<br />

2 examples, 0 failures<br />

Great, now you know this is working for the new action, but does it work for create,<br />

edit, update, and destroy? You can replace the "cannot access the new action"<br />

example you just wrote with the code from the following listing.<br />

Listing 7.9 spec/controllers/projects_controller_spec.rb<br />

{ "new" => "get",<br />

"create" => "post",<br />

"edit" => "get",<br />

"update" => "put",<br />

"destroy" => "delete" }.each do |action, method|<br />

it "cannot access the #{action} action" do<br />

sign_in(:user, user)<br />

send(method, action.dup, :id => project.id)<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 />

In this example, you use a project variable, which you need to set up by using a let,<br />

as you did for user. Under the let for user, add one for project:<br />

let(:project) { Factory(:project) }<br />

The attributes of this project object are unimportant: you only need a valid object,<br />

and Factory Girl provides that for you.<br />

The keys for the hash on the first line of listing 7.9 contain all the actions you want<br />

to ensure are protected; the values are the methods you use to make the request to<br />

the action. You use the action here to give your examples dynamic names, and you use<br />

them further down when you use the send method. The send method allows you to<br />

dynamically call methods and pass arguments to them. It’s used here because for each

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

Saved successfully!

Ooh no, something went wrong!