FactoryGirl 在创建新模型之前可以检查数据库中是否已存在模型吗?
我有以下工厂设置:
FactoryGirl.define do
factory :country do |f|
f.name "USA"
f.country_code "USA"
f.currency_code "USD"
end
factory :region do |f|
f.name "East Coast"
f.country {Country.first}
end
factory :state do |f|
f.name 'CA'
f.region {Region.first}
f.country {Country.first}
end
end
我想在该地区做什么?状态工厂将检查国家/地区数据库中是否已存在条目,如果是,则使用该条目,并且仅当未找到条目时才创建新模型。
这是我想到的一个示例,但不确定如何创建它:
factory :state do |f|
f.name 'CA'
f.region {Region.first || Factory(:region}
f.country {Country.first || Factory(:state}
end
我想要这样做的原因是将条目注入到我的数据库中,该数据库将填充表单选择字段和字段。这样我就可以用黄瓜进行测试。
I have the following factory setup:
FactoryGirl.define do
factory :country do |f|
f.name "USA"
f.country_code "USA"
f.currency_code "USD"
end
factory :region do |f|
f.name "East Coast"
f.country {Country.first}
end
factory :state do |f|
f.name 'CA'
f.region {Region.first}
f.country {Country.first}
end
end
What I want to do in the region & state factories is to check if an entry already exists in the database for Country, if yes then use that and only if no entries are found should it create a new model.
Here is an example of what I have in mind, but not sure how to create this:
factory :state do |f|
f.name 'CA'
f.region {Region.first || Factory(:region}
f.country {Country.first || Factory(:state}
end
The reason why I want to do this is to inject entries into my database which will populate form select fields & so that I can test using cucumber.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用回调来完成此操作:
You could use callbacks to accomplish this:
我认为你需要协会。
每个:地区属于:州和每个:州属于:国家
作为回报,许多州和地区。
然后您可以在工厂中使用这些关联。
查看入门指南:https://github.com/thoughtbot/factory_girl/blob /master/GETTING_STARTED.md
I think you need associations.
each :region belongs_to :state and each :state belongs_to :country
which have in return many states and regions.
You can then use these associations in your factory.
Check the Getting started guide: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md