Factory Girl Basics using Rails 3.2, Factory Girl 4.2 : Part 2


To learn how to create objects using FactoryGirl for has_many association


Step 1

Define the factory for comment model.

factory :comment do
  description 'Yes I want to buy this book'  

Step 2

Change the article factory as follows:

factory :article do
  title 'How to get rich quick'


  factory :article_with_comments do

    ignore do
      comments_count 2

    after(:create) do |article, evaluator|
      create_list(:comment, evaluator.comments_count, article: article)

Note: For version we are using, you will get:

 undefined method `comments_count' for #<FactoryGirl::SyntaxRunner:0x04a8>` if you use `transient` instead of `ignore`. 

Refer the Transient vs Ignore ticket for more details.

Step 3

You can now use the factory in your tests as follows:

  it "mapping has_many association to factory_girl : example 1" do
    article = FactoryGirl.create(:article)

    expect(article.comments.length).to eq(0)

  it "mapping has_many association to factory_girl : example 2" do
    article = FactoryGirl.create(:article_with_comments)

    expect(article.comments.length).to eq(2)

  it "mapping has_many association to factory_girl : example 3" do
    article = FactoryGirl.create(:article_with_comments, comments_count: 3)

    expect(article.comments.length).to eq(3)

You can find the repo for this project at https://github.com/bparanj/fgirl


In this article we saw how to create objects for has_many association using FactoryGirl.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.