Rick Peyton
Rick Peyton

Reputation: 69

How can I clean up this FactoryGirl build strategy?

My tests are currently working with this strategy, but there is probably a cleaner way of doing this. Any help in approaching this more intelligently would be appreciated.

I have two setup two Factories

factory :story do
  title       { Faker::Name.title }
  link        { Faker::Internet.url }
  teaser_text { Faker::Lorem.sentence(3) }
  author
  issue
  source
  headline
end

and

factory :headline do
  featured          false
  featured_story_id 1
  issue_id          1
end

A story belongs to a headline A headline has_many stories and belongs_to a featured_story (which is a story) I have a not_null constraint on the featured_story_id column

Here is what I am currently doing in my rspec test to create a headline

3.times do
  story = build(:story, issue: Issue.unpublished.first)
  story.headline.update(featured_story: story, issue: story.issue)
end

Of course would I'd prefer is to just say

create_list(:story, 3)

and let the factory work it out.

Is that possible?

Upvotes: 2

Views: 155

Answers (1)

gnerkus
gnerkus

Reputation: 12019

A simple way to achieve this is to use FactoryGirl's after(:create) callback to populate a story's headline attribute:

factory :story do
  ...

  after(:create) do |story|
    story.headline.update(featured_story: story, issue: story.issue)
  end
end

Upvotes: 1

Related Questions