I’m working through Michael Hartl’s Rails Tutorial. I’ve come to Chapter 9, Exercise 1. It asks you to add a test to verify that the admin attribute of the User class is not accessible. Here’s the User class with irrelevant portions commented out:
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
attr_protected :admin
# before_save methods
# validations
# private methods
end
And here’s the test I’m using to validate that the admin attribute is not accessible.
describe User do
before do
@user = User.new(
name: "Example User",
email: "user@example.com",
password: "foobar123",
password_confirmation: "foobar123")
end
subject { @user }
describe "accessible attributes" do
it "should not allow access to admin" do
expect do
@user.admin = true
end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
end
end
end
The test fails. It says no errors were raised, in spite of the fact that the admin attribute is protected. How can I get the test to pass?
From the Ruby documentation:
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html
Try this code instead