简体   繁体   中英

RSpec tests failing with 'unknown attribute'

I'm testing for attribute response in my model:

it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }

These attributes aren't part of the database but simply declared in my model as attr_accessible . When I don't declare them and run my tests I get:

ActiveModel::MassAssignmentSecurity::Error:
  Can't mass-assign protected attributes: password, password_confirmation

But after I declare them I get:

ActiveRecord::UnknownAttributeError:
  unknown attribute: password

Any idea why this happens?

@8vius because you are following the tutorial, but not closely enough. You need to add the line:

has_secure_password

below attr_accessible :email, :name, :role, :password, :password_confirmation

this allows you to save the plain text password and password_confirmation into memory so that you can compare the strings and enforce equality before encrypting and saving into the DB. You don't want to persist the password in plain text on the db.

attr_accessible tells Rails you allow so called mass assignement on attributes.

But attributes must exist in db or you should create getter/setter, the easiest means is:

attr_accessor :password_confirmation, :password

Anyway, sounds weird you don't store the password.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM