27.02.2013 Views

Rails%203%20In%20Action

Rails%203%20In%20Action

Rails%203%20In%20Action

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

138 CHAPTER 7 Basic access control<br />

When you run this feature, it can’t find the admin field for your users table,<br />

because you haven’t added it yet:<br />

Given there are the following users:<br />

| email | password | admin |<br />

| admin@ticketee.com | password | true |<br />

undefined method `admin=’ for #<br />

7.2 Adding the admin field to the users table<br />

You can generate a migration to add the admin field by running rails generate<br />

migration add_admin_to_users admin:boolean. You want to modify this migration so<br />

that when users are created, the admin field is set to false rather than defaulting to<br />

nil. Open the freshly generated migration and change this line<br />

add_column :users, :admin, :boolean<br />

to this:<br />

add_column :users, :admin, :boolean, :default => false<br />

When you pass in the :default option here, the admin field defaults to false, ensuring<br />

that users aren’t accidentally created as admins.<br />

The command rake db:migrate db:test:prepare runs the migration, adds the<br />

admin field to the users table, and sets up the test database. Now you see that the step<br />

is passing:<br />

Given there are the following users:<br />

| email | password | admin |<br />

| admin@ticketee.com | password | true |<br />

With this step definition implemented, run rake cucumber:ok and rake spec to make<br />

sure you haven’t broken anything. According to this output, you haven’t:<br />

16 scenarios (16 passed)<br />

152 steps (152 passed)<br />

Great! Now you can go about restricting the acts of creating, updating, and destroying<br />

projects to only those users who are admins.<br />

7.3 Restricting actions to admins only<br />

For this step, you implement a before_filter that checks not only whether the user<br />

is signed in but also whether the user is an admin.<br />

Before you write this before_filter, you write a controller spec rather than a<br />

Cucumber feature to test it. Cucumber features are great for defining a set of actions<br />

that a user can perform in your system, but controller specs are much better for<br />

quickly testing singular points, such as whether or not a user can go to a specific<br />

action in the controller. You used this same reasoning back in chapter 4 to test what<br />

happens when a user attempts to go to a project that doesn’t exist.<br />

You want to ensure that all visits to the new, create, edit, update, and destroy<br />

actions are done by admins and are inaccessible to other users. Open spec/controllers/

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

Saved successfully!

Ooh no, something went wrong!