我无法理解如何与Factory Girl建立联系。
所以基本上,代理商有很多代理商,房东和房产。当我检查我的Property工厂是否有效时,它返回false表示客户经理和房东不能为空。我如何创建这些关联?在创建房产时,它会联合“代理商”。并创造其中一个,但我需要'房东'和'代理'成为' agency'的协会太..
问题的一部分可能是我长期以来一直在盯着这个问题,所以如果它是直截了当的话就道歉!
型号:
class Agency < ActiveRecord::Base
has_many :agents
has_many :landlords
has_many :properties
end
class Property < ActiveRecord::Base
belongs_to :landlord
belongs_to :agency
belongs_to :account_manager, class_name: 'Agent', foreign_key: 'agent_id'
end
class User < ActiveRecord::Base
belongs_to :agency
end
class Agent < User
has_many :properties
end
class Landlord < User
has_many :properties
end
工厂:
FactoryGirl.define do
factory :property do
address_line_1 "13 Fake Street"
address_line_2 "Strange Lane"
town "Fake Town"
county "FakeCounty"
post_code "PA0 0WU"
beds 4
baths 2
agency
factory :invalid_property do
address_line_1 ""
end
end
end
FactoryGirl.define do
factory :agency do
name "First Agency"
telephone_number "01993 388388"
address_line_1 "1 Fake Street"
town "Fake Town"
county "FakeCounty"
post_code "BA1 4GG"
end
end
FactoryGirl.define do
factory :agent, class: User do
first_name "James"
last_name "Smith"
email "james.smith@gmail.com"
password "helloworld"
telephone_number "01935 222333"
mobile_telephone_number "07382 928777"
agency
end
factory :landlord, class: User do
first_name "Bob"
last_name "Builder"
email "bob.builder@gmail.com"
password "helloworld"
telephone_number "01935 444777"
agency
factory :invalid_landlord, class: User do
first_name ""
end
end
end
答案 0 :(得分:0)
事实证明,你无法在工厂内真正做到这种关系。
最后我删除了关联,并首先手动构建代理和任何其他关联,然后将它们传递到工厂的构建中。例如:
let(:agency) { build(:agency) }
let(:account_manager) { build(:agent, agency: agency) }
let(:landlord) { build(:landlord, agency: agency) }
let(:property) { build(:property, agency: agency, account_manager: account_manager, landlord: landlord ) }