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.

162 CHAPTER 7 Basic access control<br />

Listing 7.32 app/controllers/admin/users_controller.rb<br />

def destroy<br />

@user.destroy<br />

flash[:notice] = "User has been deleted."<br />

redirect_to admin_users_path<br />

end<br />

When you run bin/cucumber features/deleting_users.feature, the feature passes<br />

because you now have the Delete User link and its matching destroy action:<br />

1 scenario (1 passed)<br />

8 steps (8 passed)<br />

There’s one small problem with this feature, though: it doesn’t stop you from deleting<br />

yourself!<br />

7.8.1 Ensuring you can’t delete yourself<br />

To make it impossible to delete yourself, you must add another scenario to the<br />

deleting_users.feature, shown in the following listing.<br />

Listing 7.33 features/deleting_users.feature<br />

Scenario: Userscannot delete themselves<br />

When I follow "admin@ticketee.com"<br />

And I follow "Delete User"<br />

Then I should see "You cannot delete yourself!"<br />

When you run this feature with bin/cucumber features/deleting_users.feature,<br />

the first two steps of this scenario pass, but the third one fails, as you might expect,<br />

because you haven’t added the message! Change the destroy action in the<br />

Admin::UsersController to the following listing.<br />

Listing 7.34 app/controllers/admin/users_controller.rb<br />

def destroy<br />

if @user == current_user<br />

flash[:alert] = "You cannot delete yourself!"<br />

else<br />

@user.destroy<br />

flash[:notice] = "User has been deleted."<br />

end<br />

redirect_to admin_users_path<br />

end<br />

Now, before the destroy method does anything, it checks to see if the user attempting<br />

to be deleted is the current user and stops it with the "You cannot delete yourself!"<br />

message. When you run bin/cucumber features/deleting_users.feature this time,<br />

the scenario passes:<br />

2 scenarios (2 passed)<br />

16 steps (16 passed)

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

Saved successfully!

Ooh no, something went wrong!