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.

156 CHAPTER 7 Basic access control<br />

expected #has_content?("newadmin@ticketee.com (Admin)")<br />

to return true, got false<br />

This failure occurs because admin isn’t a mass-assignable attribute and therefore isn’t<br />

set and because the user’s admin status isn’t displayed anywhere on the page. One<br />

thing at a time. First, change the create action in Admin::UsersController to set the<br />

admin field before you attempt to save the user, as shown in the following listing.<br />

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

...<br />

@user = User.new(params[:user])<br />

@user.admin = params[:user][:admin] == "1"<br />

if @user.save<br />

...<br />

This code sets the admin attribute on the user, which is one of the two things you need<br />

to get this step to pass. The second problem is that only the user’s email address is displayed:<br />

no text appears to indicate they’re a user. To get this text to appear, change<br />

the line in app/views/admin/users/index.html.erb from this<br />

<br />

to this:<br />

<br />

By not calling any methods on the user object and attempting to write it out of the<br />

view, you cause Ruby to call to_s on this method. By default, this outputs something<br />

similar to the following, which isn’t human friendly:<br />

#<br />

You can override the to_s method on the User model to provide the string containing<br />

the email and admin status of the user by putting the following code inside the class<br />

definition in app/models/user.rb, underneath the attr_accessible line:<br />

def to_s<br />

"#{email} (#{admin? ? "Admin" : "User"})"<br />

end<br />

Now that the admin field is set and displayed on the page, the feature should pass<br />

when you run bin/cucumber features/creating_users.feature:<br />

3 scenarios (3 passed)<br />

33 steps (33 passed)<br />

This is another great time to commit, and again, run rake cucumber:ok spec to make<br />

sure everything works:<br />

28 scenarios (28 passed)<br />

288 steps (288 passed)<br />

# and<br />

14 examples, 0 failures, 7 pending

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

Saved successfully!

Ooh no, something went wrong!