【发布时间】:2014-07-28 03:45:52
【问题描述】:
刚开始测试,正在尝试将 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_id,而是通过 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
现在对于工厂,我有:
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?
【问题讨论】:
标签: ruby-on-rails rspec associations factory-bot