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.

Restricting delete access<br />

Listing 8.11 features/hidden_links.feature<br />

Scenario: New ticket link is shown to a user with permission<br />

Given "user@ticketee.com" can view the "TextMate 2" project<br />

And "user@ticketee.com" can create tickets on the "TextMate 2" project<br />

And I am signed in as "user@ticketee.com"<br />

When I follow "TextMate 2"<br />

Then I should see "New Ticket"<br />

Scenario: New ticket link is hidden from a user without permission<br />

Given "user@ticketee.com" can view the "TextMate 2" project<br />

And I am signed in as "user@ticketee.com"<br />

When I follow "TextMate 2"<br />

Then I should not see the "New Ticket" link<br />

Scenario: New ticket link is shown to admins<br />

Given I am signed in as "admin@ticketee.com"<br />

When I follow "TextMate 2"<br />

Then I should see the "New Ticket" link<br />

These three scenarios test all three permutations of users who could possibly see this<br />

page. Users with permission and admins should be able to see the link, and users without<br />

permission should not. When you run this feature with bin/cucumber features/<br />

hidden_links.feature, the second scenario fails:<br />

Expected to not see the "New Ticket" link, but did.<br />

(RSpec::Expectations::ExpectationNotMetError)<br />

This error occurs because the link is visible independently of whether or not the user<br />

has permission. With these scenarios in place, you can work on making them pass. You<br />

can wrap the New Ticket in a helper method, similar to the admins_only helper used<br />

in chapter 6. Open app/views/projects/show.html.erb, and change the New Ticket link<br />

from this<br />

<br />

to this:<br />

<br />

<br />

<br />

Currently, this authorized? method is undefined. This is the method you need in<br />

views all across your application to determine if the user has permission to see the specific<br />

action and if that user is an admin. Because you’ll use this helper everywhere,<br />

define it inside app/helpers/application_helper.rb, as shown here:<br />

def authorized?(permission, thing, &block)<br />

block.call if can?(permission.to_sym, thing) ||<br />

current_user.try(:admin?)<br />

nil<br />

end<br />

This helper uses CanCan’s can? method to check if the user is authorized to perform<br />

this action. If so, then all is fine and dandy. If not, then you check to see if the<br />

195

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

Saved successfully!

Ooh no, something went wrong!