vendredi 8 janvier 2016

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?

Aucun commentaire:

Enregistrer un commentaire