我如何清理这个 FactoryGirl 构建策略?
How can I clean up this FactoryGirl build strategy?
我的测试目前正在使用此策略,但可能有更简洁的方法来执行此操作。任何有助于更智能地解决这个问题的帮助将不胜感激。
我有两个设置两个工厂
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
一个故事属于一个标题
标题 has_many 个故事和 belongs_to 个 featured_story(这是一个故事)
我在 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 的 after(:create) 回调来填充故事的 headline
属性:
factory :story do
...
after(:create) do |story|
story.headline.update(featured_story: story, issue: story.issue)
end
end
我的测试目前正在使用此策略,但可能有更简洁的方法来执行此操作。任何有助于更智能地解决这个问题的帮助将不胜感激。
我有两个设置两个工厂
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
一个故事属于一个标题 标题 has_many 个故事和 belongs_to 个 featured_story(这是一个故事) 我在 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 的 after(:create) 回调来填充故事的 headline
属性:
factory :story do
...
after(:create) do |story|
story.headline.update(featured_story: story, issue: story.issue)
end
end