我的测试目前正在使用此策略,但可能有更简洁的方法来执行此操作。如果您能帮助我们更明智地解决这个问题,我们将不胜感激。
我有两个设置两个工厂
factory :story do
title { Faker::Name.title }
link { Faker::Internet.url }
teaser_text { Faker::Lorem.sentence(3) }
author
issue
source
headline
end
和
factory :headline do
featured false
featured_story_id 1
issue_id 1
end
一个故事属于一个标题 一个标题有很多故事并且属于一个特色故事(这是一个故事) 我对 featured_story_id 列有一个 not_null 约束
这是我目前在 rspec 测试中创建标题的方法
3.times do
story = build(:story, issue: Issue.unpublished.first)
story.headline.update(featured_story: story, issue: story.issue)
end
当然我更愿意直接说
create_list(:story, 3)
让工厂解决。
这可能吗?
最佳答案
实现此目的的一个简单方法是使用FactoryGirl's after(:create)填充故事的 headline
属性的回调:
factory :story do
...
after(:create) do |story|
story.headline.update(featured_story: story, issue: story.issue)
end
end
关于ruby-on-rails - 我如何清理这个 FactoryGirl 构建策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35538557/