Fernando
Fernando

Reputation: 4629

FactoryGirl: set has_many association on creation

This issue is happening in an upgrade that I'm working from Rails 3.2 to Rails 4.2. It might be related to the many things that Rails 4 broke.

I have the following factory:

factory :account do
  sequence(:email) {|n| "email#{n}@example.org" }
  sequence(:name) {|n| "Name #{n}" }
end

This model has an has_many association called ips. At a specific test, I need to set the account with an ip. In Rails 3.2 I was able to do this:

FactoryGirl.create(:account, :ips => [FactoryGirl.create(:ip)])

But in Rails 4 I get an exception:

ActiveRecord::RecordInvalid: Validation failed: Ips is invalid

I was able to verify that I'm not longer able to override an has_many association. Example:

account = FactoryGirl.build(:account)
account.ips = [FactoryGirl.create(:ip)]
account.save!

It will also throw an exception.

As a side note, using << works fine but that's not what I want since I want to delete any IPs that are assigned to the account and only set the new one.

What is the proper way of doing this in Rails 4?

Upvotes: 2

Views: 70

Answers (1)

user5800342
user5800342

Reputation:

For this I would recommend using a trait with an after create. So it would look something like this:

  FactoryGirl.define do
    factory :account do
      sequence(:email) {|n| "email#{n}@example.org" }
      sequence(:name) {|n| "Name #{n}" }
    end

    trait :with_ip do
      transient do
        ip_count 5
      end

      after(:create) do |account, evaluator|
        create_list(:ip, evaluator.ip_count, account: account)
      end
    end
  end

See this for further reference: https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md

Upvotes: 2

Related Questions