brycemcd
brycemcd

Reputation: 4523

Creating an object with many associated objects

I see this pattern a lot in my rspec tests and I've tried a few times to clean it up a bit with no luck. I have a factory, blog of course, and a factory post. Blog has_many posts.

I generally use FactoryGirl for this purpose and the factory would look like this:

FactoryGirl.define :blog do |b|
  b.title "my blog"
end

FactoryGirl.define :post do |p|
  p.author "some dude"
  p.content
end

This is the code smell in my rspec tests:

@blog = FactoryGirl.create(:blog)
5.times { FactoryGirl.create(:post, :blog => @blog) }

Seems like I should be able to define a new factory of a fully hydrated blog post:

FactoryGirl.define :blog_with_posts, :parent => :blog do |bwp|
   5.times { bwp.association(:post) }
end

I haven't been able to find an approach that actually works.

Upvotes: 0

Views: 100

Answers (1)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

FactoryGirl.define do
  factory :post do
    author "dude"
    content { Faker::Lorem.paragraph }
    blog
  end

  factory :blog do
    title "title"
    factory :blog_with_posts do

      ignore do
        posts_count 5
      end

      after(:create) do |blog, evaluator|
        FactoryGirl.create_list(:post, evaluator.posts_count, blog: blog)
      end

    end
  end
end

Upvotes: 1

Related Questions