1

我有一个User has_many :accounts, through: :roles和一个User has_many :owned_accounts, through: :ownerships,我在哪里使用 STI Ownership < Roles。我无法为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

我有用户、帐户和角色的工作工厂;但是,我无法为 Ownership 和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)>'
4

1 回答 1

3

错误消息是因为您需要指定父级,否则它将假定工厂定义用于该名称的 ActiveRecord 类。

factory :owned_account, :parent => :account do
  name "ACME Corporation"
end
于 2012-05-18T18:29:47.110 回答