Reputation: 3659
I have two models Board
and Category
with relation has_many/belongs_to.
In Board
I have after_create
callback creating default Category for it.
So when I create Board, it automatically creates default Category for it.
after_create do
categories.create(name: "All Links", description: nil)
end
Now I create basic :board factory:
factory :board do
name {Faker::Lorem.sentence(rand(5)+1)}
description {Faker::Lorem.paragraph(rand(5))}
end
I have Board instance method: root_category which returns this default Category.
My question is, how can I create :category factory based on this :board.root factory, and #root_category method? Something like:
factory :category do
1. board = FactoryGirl.create(:board)
2. returns board.root_category as a factory output.
end
Upvotes: 0
Views: 1018
Reputation: 24815
Your question can be solved directly but there are more concerns than solution.
To answer exactly your question, you don't need a "category" factory to create root category for a board. The callback will be executed at model level, no need interfering of FactoryGirl.
It's not good practice to use callbacks on external models/classes. Category is outside of Board, so Board should not call Category in it's callbacks which is supposed a private space. Instead, a better approach is to add root category to a board in BoardsController's #create
You may need to reconsider your modelling. In common sense a model and its category would be better in many to many relationship. Suppose, in your case, a board has category "Coding", then "Coding" category can no longer be used on other board in your modelling!
Upvotes: 1