Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Rails Class Attribute Inaccessible - Rails Tutorial Chapter 9, Exercise 1

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: "[email protected]",
                     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?

like image 661
michaelmichael Avatar asked Jul 04 '26 12:07

michaelmichael


1 Answers

From the Ruby documentation:

Mass assignment security provides an interface for protecting attributes from end-user assignment.

http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html

Try this code instead

describe "accesible attributes" do
  it "should not allow access to admin" do
    expect do
      User.new(admin: true) 
    end.should raise_error(ActiveModel::MassAssignmentSecurity::Error)
  end
end
like image 95
Alma Avatar answered Jul 06 '26 05:07

Alma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!