FactoryBot Realtionship:Association in Inherit factory
FactoryBot Realtionship: Association in Inherit factory
描述
我定义了作者、产品和事件工厂。
并且产品可以具有 author_id 值或 null。
和事件可以有 product_id 值或空值。
我定义了以下关联但没有用。
你能告诉我如何定义关联吗?
factory :author do
first_name FFaker::Name.first_name
last_name FFaker::Name.last_name
end
factory :product do
name Faker::Book.title
factory :product_with_author do
author
end
end
factory :event do
name FFaker::Lorem.words
start_time Time.now-3.hours
end_time Time.now+1.hour
factory :upcoming_event do
is_active true
product_with_author #I want a product with an author field, "undefined Method Error"
# I also tried followings but not working, and I have no idea how to define this
# product :product_with_author (Require Class but Symbol assigned error)
# product product_with_author (Implicit Conversion error)
end
product
end
我不确定这些关联,但像这样的东西应该有用。它通过为产品定义关联和工厂来为产品创建作者。至于事件,您可以在 before(:create)
或 after(:create)
或 before(:build)
或 after(:build)
中执行此操作。正如我在代码片段中所述,我不知道您的关联,但您可以在该块中将事件传递给产品,反之亦然。
我发现这个 cheatsheet 对我的工厂机器人问题很有帮助
factory :author do
first_name FFaker::Name.first_name
last_name FFaker::Name.last_name
end
factory :product do
name Faker::Book.title
association :author, factory: :author
end
factory :event do
name FFaker::Lorem.words
start_time Time.now-3.hours
end_time Time.now+1.hour
factory :upcoming_event do
after(:create) do |event, evaluator|
# I'm not sure how event and product are associated
create(:product)
end
end
end
描述
我定义了作者、产品和事件工厂。 并且产品可以具有 author_id 值或 null。 和事件可以有 product_id 值或空值。 我定义了以下关联但没有用。 你能告诉我如何定义关联吗?
factory :author do
first_name FFaker::Name.first_name
last_name FFaker::Name.last_name
end
factory :product do
name Faker::Book.title
factory :product_with_author do
author
end
end
factory :event do
name FFaker::Lorem.words
start_time Time.now-3.hours
end_time Time.now+1.hour
factory :upcoming_event do
is_active true
product_with_author #I want a product with an author field, "undefined Method Error"
# I also tried followings but not working, and I have no idea how to define this
# product :product_with_author (Require Class but Symbol assigned error)
# product product_with_author (Implicit Conversion error)
end
product
end
我不确定这些关联,但像这样的东西应该有用。它通过为产品定义关联和工厂来为产品创建作者。至于事件,您可以在 before(:create)
或 after(:create)
或 before(:build)
或 after(:build)
中执行此操作。正如我在代码片段中所述,我不知道您的关联,但您可以在该块中将事件传递给产品,反之亦然。
我发现这个 cheatsheet 对我的工厂机器人问题很有帮助
factory :author do
first_name FFaker::Name.first_name
last_name FFaker::Name.last_name
end
factory :product do
name Faker::Book.title
association :author, factory: :author
end
factory :event do
name FFaker::Lorem.words
start_time Time.now-3.hours
end_time Time.now+1.hour
factory :upcoming_event do
after(:create) do |event, evaluator|
# I'm not sure how event and product are associated
create(:product)
end
end
end