0
votes

I have a User model that is only valid when there is at least one Address:

class User
  has_many :addresses
  validates :addresses, length: { miniumum: 1}
end

class Address
  belongs_to :user
end

I tried defining my FactoryBot factory like this:

FactoryBot.define do
  factory :user do
    association :address
    name 'test'
  end
end

When creating a user with create(:user), there's an error that user could not be saved due to missing address. It seems the association is only created after the user is created (which obviously creates a validation error). What's the correct way to build my factory?

Thanks

2
How does it work in real life? I mean - how can I set a user_id for an address without creating a user?MrShemek
By saving the user and a minimum of 1 address through a nested form, in which user accepts nested attributes for the address. This part is already working, just wanted to write tests for this.bo-oz
Possible duplicate of FactoryBot - create nested objectsberkes

2 Answers

0
votes

Try with:

FactoryBot.define do
  factory :user do
    name 'test'

    before(:create) do |user|
      user.addresses << build(:address, user: user)
    end
  end
end

Please remember to create a factory for address as well.

0
votes

association attribute, should only be used if the model contains the foreign key (the model which you declared belongs_to on it). Remove association :address from your factory and use before(:create) callback to build addresses before saving user:

FactoryBot.define do
  factory :user do
    name 'test'
    before(:create) { |object| object.addresses.build() }
  end
end