FactoryGirl模型规范与关联

时间:2014-07-27 18:22:35

标签: ruby-on-rails rspec associations factory-bot

测试新手,我正在尝试将FactoryGirl添加到模型测试中。我的挑战是我在用户和帐户之间有一个has_one关系,但是通过帐户模型中的owner_id字段。

以下测试工作

describe Client do
  it "is valid with a name and account" do
    user = User.create(email: "me@example.com", 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

我正在尝试修改以便使用FactoryGirl:

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

客户端模型属于具有__ user用户的帐户。关联是通过owner_id而不是user_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

现在工厂,我有:

FactoryGirl.define do
  factory :user do
    email "john@example.com"
    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

如何从关联中获取user_id并分配给帐户的owner_id?

1 个答案:

答案 0 :(得分:2)

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

我需要将:owner_id更改为:帐户工厂中关联的所有者。