使用 FactoryGirl 设置受保护的属性
FactoryGirl 不会设置我的受保护属性 user.confirmed
。这里的最佳实践是什么?
Factory.define :user do |f|
f.name "Tim" # attr_accessible -- this works
f.confirmed true # attr_protected -- doesn't work
end
我可以在使用我的工厂后执行 @user.confirmed = true
,但这需要在大量测试中进行大量重复。
FactoryGirl won't set my protected attribute user.confirmed
. What's the best practice here?
Factory.define :user do |f|
f.name "Tim" # attr_accessible -- this works
f.confirmed true # attr_protected -- doesn't work
end
I can do a @user.confirmed = true
after using my factory, but that's a lot of repetition across a lot of tests.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
after_create
钩子有效:Using an
after_create
hook works:创建用户时,您必须将其传递到哈希中,因为 FactoryGirl 正在保护它免遭批量分配。
You would have to pass it into the hash when you create the user since FactoryGirl is protecting it from mass-assignment.
另一种方法是使用 Rails 的内置角色,如下所示:
当批量分配 FactoryGirl 广播此角色时,使此模式成为可能。
优点:使工厂保持快速、简单和干净(回调中的代码更少)
缺点:您正在更改测试的模型代码:(
一些未经测试的建议来解决缺点:
Another approach is to use Rails' built in roles like this:
When mass-assigning FactoryGirl broadcasts this role, making this pattern possible.
Pros: Keeps factories fast, simple, and clean (less code in callbacks)
Cons: You are changing your model code for your tests :(
Some untested suggestions to address the Con: