I defined author, product and event factory. and product can have author_id value or null. and event can have product_id value or null. I defined the association following but no works. Can you give me an idea how to define the association?
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
I'm not sure of the associations, but something like this should work. It creates an author for the product by defining the association and factory for it. As for the event, you can do that in a hook, before(:create)
or after(:create)
or before(:build)
or after(:build)
. As I stated in the snippet, I'm unaware of your associations, but you could pass the event to the product or vice versa in that block.
I find this cheatsheet very helpful in my factory bot issues
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