工厂女孩的额外论点
我需要将额外的参数传递给工厂女孩以在回调中使用。像这样的东西(但实际上更复杂):
Factory.define :blog do |blog|
blog.name "Blah"
blog.after_create do |blog|
blog.posts += sample_posts
blog.save!
end
end
然后用这样的东西创建它:
Factory.create(:blog, :sample_posts => [post1, post2])
有什么想法如何做到这一点?
I need to pass extra arguments to factory girl to be used in a callback. Something like this (but more complex really):
Factory.define :blog do |blog|
blog.name "Blah"
blog.after_create do |blog|
blog.posts += sample_posts
blog.save!
end
end
and then create it with something like this:
Factory.create(:blog, :sample_posts => [post1, post2])
Any ideas how to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于瞬态属性,现在可以在没有任何“黑客”的情况下实现这一点(请参阅问题 # 的评论49)
示例:
对于 Factory Girl 版本 < 5.0:
This is now possible without any "hacks" thanks to transient attributes (see comment on issue #49)
example:
For Factory Girl versions < 5.0:
一种选择是为
after_create
挂钩检查的额外帖子创建一个虚拟访问器:One option would be to create a virtual accessor for extra posts that the
after_create
hook checks:显然,如果没有需要修改模型本身的解决方法,目前这是不可能的。此错误报告于:http://github.com/thoughtbot/factory_girl/issues#问题/49
Apparently, this is not possible at the moment without workarounds that require modifying the model itself. This bug is reported in: http://github.com/thoughtbot/factory_girl/issues#issue/49
另一种选择是使用
build
而不是create
并将:autosave
添加到集合中:Another option would be to use
build
instead ofcreate
and add:autosave
to the collection:如果您要在 Factorygirl 文件中打开课程,我建议这样做,
以便您打开课程,而不是覆盖它
if you are opening the class inside the factorygirl file, i suggest doing it like
so that you are opening the class, instead of overwriting it