在黄瓜中与factory_girl建立关联的最佳实践是什么?
我通常使用此步骤来设置与factory_girl的记录:
Given /^the following (.+) records?:$/ do |factory, table|
table.hashes.each do |hash|
Factory(factory, hash)
end
end
这是我在设置关联时的解决方法:
Given the following group record:
| id | name |
| 1 | foo |
And the following item records:
| name | group_id |
| bar | 1 |
| baz | 1 |
# ...
我知道这很糟糕。从域人员的角度来看,使用 ids 会使整个事情变得脆弱和神秘。
所以,我的问题是——与factory_girl 建立关联以及像上面这样的表参数的最佳实践是什么?
I normally use this step to set up records with factory_girl:
Given /^the following (.+) records?:$/ do |factory, table|
table.hashes.each do |hash|
Factory(factory, hash)
end
end
And here's my work-around when setting up associations:
Given the following group record:
| id | name |
| 1 | foo |
And the following item records:
| name | group_id |
| bar | 1 |
| baz | 1 |
# ...
I know this is bad. Using ids makes the whole thing brittle and cryptic from the vantage of the domain person.
So, my question is -- what would be the best practice to set up an association with factory_girl and a table argument like the one above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在工厂中定义多个关联。
如下所示:
执行
Factory(:group)
将创建包含两个项目的组 uplet。You can define multiple associations in a factory.
Like the following :
Doing a
Factory(:group)
will create your group uplet with two items in it.只是回答我自己的问题: Pickle
Just to answer my own question: Pickle
您可以使用定义的 FactoryGirl Cucumber 步骤:
https://github.com/thoughtbot/factory_girl/blob/master /lib/factory_girl/step_definitions.rb
您只需一个 Cucumber 步骤即可设置您的项目和组:
这样做时,组“Bar”的创建使用“find_or_create_by”功能,因此第一个调用创建组,接下来的 2 个调用找到已创建的组。
这样,所有 3 个项目将具有相同的组“Bar”,并且您可以根据需要创建任意数量的分组项目。
You can use the defined FactoryGirl Cucumber steps:
https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/step_definitions.rb
You can setup your items and your group(s) in just one Cucumber step:
When doing it like this, the creation of group 'Bar' is using 'find_or_create_by' functionality, so the first call creates the group, the next 2 calls finds the already created group.
In this way all 3 items will have same group 'Bar', and you can create as many grouped items as you need.