我如何create(:listing, :for_car)
和create(:firm, :for_car)
,但允许它们具有相同的普通汽车记录?
理想情况下,我想做create(:listing)
并让它创建,用户,然后是汽车(belongs_to用户(,然后是列表(belongs_to汽车(,然后是公司(belongs_to车(。在这种情况下,Car 是相同的确切记录,而不是两个不同的 Car 记录。
所以我不必调用多个create
方法。我怎样才能做到这一点?
FactoryBot.define do
factory :user, class: "User" do
email { Faker::Internet.email }
password { "bla" }
password_confirmation { "bla" }
end
factory :car, class: "Car" do
color { "black" }
association :user, factory: :user
end
factory :truck, class: "Truck" do
size { "15" }
association :user, factory: :user
end
factory :bike, class: "Bike" do
style { "road" }
association :user, factory: :user
end
factory :listing, class: "Listing" do
for_car # default
trait :for_car do
association :listable, factory: :car
end
trait :for_truck do
association :listable, factory: :car
end
trait :for_bike do
association :listable, factory: :car
end
end
factory :firm, class: "Firm" do
for_car # default
trait :for_car do
association :listable, factory: :car
end
trait :for_truck do
association :listable, factory: :car
end
trait :for_bike do
association :listable, factory: :car
end
end
factory :store, class: "Store" do
for_car # default
trait :for_car do
association :listable, factory: :car
end
trait :for_truck do
association :listable, factory: :car
end
trait :for_bike do
association :listable, factory: :car
end
end
end
你可以这样做:
car_factory.rb
FactoryBot.define do
factory :car, class: Car do
color { "black" }
user
end
end
(请注意,您不需要使用该冗长的语法(
listing_factory.rb
FactoryBot.define do
factory :listing, class: "Listing" do
car
end
end
这是假设列表有一个名为car
的字段。在这种情况下,FactoryBot 可以为您找到合适的工厂。
然后在您的规范中,您可以像这样覆盖默认值:
let(:car) { create(:car) }
let(:truck) { create(:truck) }
let(:car_listing) { create(:listing) }
let(:truck_listing) { create(:listing, car: truck) }
在create
方法中的工厂名称之后传递的任何参数都将传入以覆盖工厂内的任何默认值。