工厂女孩新手:调用(而不是创建)现有工厂作为协会
我有一些女工厂,它们与其他工厂有联系。例如:
FactoryGirl.define do
factory :user do |f|
f.sequence(:email) { |n| "user#{n}@example.com" }
f.password "foobar"
f.password_confirmation { |u| u.password }
f.role_id 2
f.association :role, :factory => :role
end
end
问题是,如果我调用 Factory(:user) 两次,我会收到重复错误(role.name 列上有唯一性约束)
所以问题是:我如何指定上面应该创建:角色工厂(如果尚不存在),但如果不存在则使用现有角色工厂?
I have some factorygirl factories that involve associations to other factories. For example:
FactoryGirl.define do
factory :user do |f|
f.sequence(:email) { |n| "user#{n}@example.com" }
f.password "foobar"
f.password_confirmation { |u| u.password }
f.role_id 2
f.association :role, :factory => :role
end
end
The problem is that if I call Factory(:user) twice, I get a duplication error (there's a uniqueness constraint on the role.name column)
So the question is: how do I specify that the above should create the :role factory if it doesn't already exist, but use the existing one if it doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在工厂角色名称上使用序列。例如
定义角色名称序列,如 in
并定义 Factory 角色,如 in
通过这样做,每次都会创建一个新角色,但具有不同的 role_name。您可以通过在每个测试中创建角色来将角色传递给 Factory.build。但我觉得那样很麻烦。
Why dont you use a sequence on Factory role name. For example
define sequence for role name like in
and define Factory role like in
By doing this, each time a new role will be created but with a different role_name. You could pass the role to Factory.build by creating the role in each test. But I find that cumbersome.