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

»

Rails Testing

Rails Testing

I have often been told and red not to test the database. To avoid useless round trips and that my tests should be testing the code, not the database. That is the key to fast testing. But how fast exactly does this change? I took it upon myself to figure it out. I wanted to know the affects of slow vs fast testing and measure it.

Slow tests often come from round trip to the database. I decided to measure the performance impact using a gem I generally use for testing: FactoryGirl

»