我在为FactoryGirl的多态关联设置工厂时遇到了问题。我的模型和工厂设置如下所示:
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
class Customer < ActiveRecord::Base
has_one :address, as: :addressable
end
factory :address do
village Faker::Address.city
upazilla Faker::Address.street_name
ward Faker::Address.street_address
district Faker::Address.state
association :addressable
end
factory :customer ,class: Customer do
recharge_token 10
date_of_birth Faker::Date.backward(100)
manager
after(:create) do |customer|
customer.address = create(:address, addressable: customer)
#create( :address, addressable: customer)
end
end
测试套件中断了以下错误消息
vendor/cache/ruby/2.2.0/gems/factory_girl-4.7.0/lib/factory_girl/linter.rb:12:in `lint!': The following factories are invalid: (FactoryGirl::InvalidFactoryError)
* address - Factory not registered: addressable (ArgumentError)
This正是我的问题,但不幸的是他的解决方案对我不起作用。谢谢大家的时间!
答案 0 :(得分:9)
明确指定工厂:
factory :address do
association :addressable, factory: :customer
end
或在has_one
列表中的其他模型上创建关联after create
:
factory :customer do
after(:create) do |customer|
customer.address = create(:address, addressable: customer)
end
end