Joining FactoryGirl has_many with bi-directional presence check creates an extra record

I'm new to FactoryGirl, and I'm having problems with this particular use case, which doesn't seem to be covered in the documentation.

I have two models: Person and Book. A person has many books, a book belongs to a person, and both have validations that require each other to be present. (A book must have a person, and a person must have at least one book.)

class Person < ActiveRecord::Base
  has_many :books, inverse_of: :person
  validates :books, presence: true
end

class Book < ActiveRecord::Base
  belongs_to :person
  validates :person, presence: true
end

I need factories for Person and Book that meet the minimum requirements for validating their models. The factory person must create at least one book, and the factory book must create one Person.

Here are my plants:

FactoryGirl.define do
  factory :person do

    transient do
      books_count 1
    end

    after :build do |person, evaluator|
      person.books << FactoryGirl.build_list(:book, evaluator.books_count, person: person)
    end
  end
end

FactoryGirl.define do
  factory :book do
    association :person
  end
end

This code works for FactoryGirl.create(:person). However, when I run FactoryGirl.create(:book), the following happens:

  • Book created.
  • .
  • , Person factory.

Book factory, book_count 0, association :person, books_count: 0, ActiveRecord::RecordInvalid: Validation failed: Books can't be blank, ActiveRecord , Person .

, factory .

, FactoryGirl.create(:book) , ?

+4
1

@Anthony :

, , . , :

class Person < ActiveRecord::Base
  has_many :books, inverse_of: :person
  validates :books, presence: true
end

, :

class Book < ActiveRecord::Base
  belongs_to :person
  validates :person, presence: true
end

, , Active Record.

+1

All Articles