简体   繁体   English

RSpec测试失败,并显示“未知属性”

[英]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 . 这些属性不是数据库的一部分,而只是在我的模型中声明为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. @ 8vius,因为您正在关注本教程,但不够紧密。 You need to add the line: 您需要添加以下行:

has_secure_password

below attr_accessible :email, :name, :role, :password, :password_confirmation 在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. 这使您可以将纯文本密码和password_confirmation保存到内存中,以便在加密并保存到数据库之前可以比较字符串并强制执行相等性。 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. attr_accessible告诉Rails您允许对属性进行所谓的批量分配。

But attributes must exist in db or you should create getter/setter, the easiest means is: 但是属性必须存在于db中,或者您应该创建getter / setter,最简单的方法是:

attr_accessor :password_confirmation, :password

Anyway, sounds weird you don't store the password. 无论如何,听起来很奇怪,您没有存储密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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