FactoryGirl (1-1)
FactoryGirl (1-1 Associations)
This blog post goes about a common problem I’ve haven’t found much documentation on.
It follows issues mentioned of multiple places like here and variations of it.
I’ve written some code to illustrate the problem on my Github FactoryGirl-Problem to accompany this.
Problem
How to create factories such that the association is a 1-1, and all models can be created independently.
Models
# app/models/user.rb
class User < ActiveRecord::Base
has_one :profile
end
# app/models/profile.rb
class Profile < ActiveRecord::Base
belongs_to :user
validates :user,
presence: true,
uniqueness: true
end
How to create the factories to get the following tests to pass
»