Steve
Steve

Reputation: 2666

FactoryGirl Model Spec with Associations

New to testing and am trying to add FactoryGirl to a model test. My challenge is that I have a has_one relationship between user and account but via an owner_id field in the accounts model.

The following test works

describe Client do
  it "is valid with a name and account" do
    user = User.create(email: "[email protected]", password: "pw", password_confirmation: "pw")
    account = Account.create(name: "Company One", owner_id: user.id)
    client = account.clients.new(name: "TestClient")
    expect(client).to be_valid
  end
end

I am trying to modify so that uses FactoryGirl:

describe Client do
  it "has a valid factory" do
    expect(build(:client)).to be_valid
  end
end

The client model belongs_to an account which has_one user. Instead of user_id the association is via owner_id.

class User < ActiveRecord::Base
  has_one :owned_account, class_name: 'Account', foreign_key: 'owner_id'
  has_many :user_accounts, dependent: :destroy
  has_many :accounts, through: :user_accounts
end

class Account < ActiveRecord::Base
  belongs_to :owner, class_name: 'User'
  has_many :user_accounts, dependent: :destroy
  has_many :users, through: :user_accounts
  has_many :clients, dependent: :destroy
end

class Client < ActiveRecord::Base
  belongs_to :account
  default_scope { where(account_id: Account.current_id)}
end

Now for Factories, I have:

FactoryGirl.define do
  factory :user do
    email "[email protected]"
    password "pw"
    password_confirmation "pw"
  end
end

FactoryGirl.define do
  factory :account do
    association :owner_id, factory: :user
    name "Account One"
  end
end

FactoryGirl.define do
  factory :client do
    association :account
    name "Test Client"
  end
end

How do I get the user_id from the association and assign to the account's owner_id?

Upvotes: 0

Views: 1120

Answers (1)

Steve
Steve

Reputation: 2666

FactoryGirl.define do
  factory :account do
    association :owner, factory: :user
    name "Account One"
  end
end

I needed to change :owner_id to :owner for the association in the accounts factory.

Upvotes: 2

Related Questions