我有User has_many :accounts, through: :roles
和User has_many :owned_accounts, through: :ownerships
,我正在Ownership < Roles
使用STI。我无法为Ownership
模型和owned_account
关联编写工作工厂,我的测试失败了。
class User < ActiveRecord::Base
has_many :roles
has_many :accounts, through: :roles
has_many :ownerships
has_many :owned_accounts, through: :ownerships
end
class Account < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
end
class Role < ActiveRecord::Base
belongs_to :users
belongs_to :accounts
end
class Ownership < Role
end
我有工作用户,帐户和角色工厂;但是,我无法为所有权和owned_accounts协会编写工厂:
FactoryGirl.define do
factory :user do
name "Elmer J. Fudd"
end
factory :account do
name "ACME Corporation"
end
factory :owned_account do
name "ACME Corporation"
end
factory :role do
user
account
end
factory :ownership do
user
owned_account
end
end
我从这些测试开始,但是我得到了一个未初始化的常量错误,并且所有测试都失败了:
describe Ownership do
let(:user) { FactoryGirl.create(:user) }
let(:account) { FactoryGirl.create(:owned_account) }
before do
@ownership = user.ownerships.build
@ownership.account_id = account.id
end
subject { @ownership }
it { should respond_to(:user_id) }
it { should respond_to(:account_id) }
it { should respond_to(:type) }
end
1) Ownership
Failure/Error: let(:account) { FactoryGirl.create(:owned_account) }
NameError:
uninitialized constant OwnedAccount
# ./spec/models/ownership_spec.rb:17:in `block (2 levels) in <top (required)>'
# ./spec/models/ownership_spec.rb:21:in `block (2 levels) in <top (required)>'
答案 0 :(得分:3)
错误消息是因为您需要指定parent,或者它将假定工厂定义是针对该名称的ActiveRecord类。
factory :owned_account, :parent => :account do
name "ACME Corporation"
end