简体   繁体   中英

Creating associations with FactoryGirl

I have a User has_many :accounts, through: :roles and a User has_many :owned_accounts, through: :ownerships , I'm using STI where Ownership < Roles . I can't write a working factory for the Ownership model and the owned_account association, and my tests are failing.

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

I have working factories for User, Account, and Role; I can't write a factory for Ownership and the owned_accounts association, however:

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

I started with these tests, but I get an uninitialized constant error and all the tests fail:

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)>'

The error message is because you need to specify parent, or it will assume the factory definition is for an ActiveRecord class of that name.

factory :owned_account, :parent => :account do
  name "ACME Corporation"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM