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.

Answers


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

Need Your Help

NodeJS reading dynamically directory

javascript node.js readfile readdir

I am making a tool that reads text files from a directory. I am using NodeJS fs.readdir and fs.readFile functions. The problem is that if I add a new folder I have to run the server again. Do you h...