When trying to build namespaced associations, Factorybot does not register the namespace, but rather uses its own despite defining it just like documentation (and every thread on SO says).
Model Admin::TicketCategory
class Admin::TicketCategory < ApplicationRecord
has_many :tickets
end
And its factory:
FactoryBot.define do
factory :ticket_category, class: Admin::TicketCategory do |f|
f.text { Faker::Commerce.product_name }
end
end
The Ticket
model:
class Ticket < ApplicationRecord
belongs_to :user
belongs_to :service_rep, class_name: 'User', foreign_key: :user_id
belongs_to :ticket_category
belongs_to :ticket_status
belongs_to :ticket_urgency
has_many :ticket_comments
end
And its factory:
FactoryBot.define do
factory :ticket do |f|
f.user
f.ticket_category
f.subject { Faker::Lorem.sentence }
f.body { Faker::Lorem.paragraph }
f.ticket_urgency { admin_ticket_urgency }
f.ticket_status { admin_ticket_status }
f.service_rep { user }
end
end
When I try to validate the Ticket
model, this error comes up:
1) Ticket has a valid factory
Failure/Error: expect(FactoryBot.create(:ticket)).to be_valid
NameError:
uninitialized constant Ticket::TicketCategory
Any help would be greatly appreciated!
Here's how rails works when it comes to namespaced models: It will try to find out the associated model in current namespace.
Let's start with the associations that you defined:
In Admin::TicketCategory
it should have has_many: tickets, class_name: "Ticket"
(assuming you have ticket_category_id
in Ticket
model). And in your Ticket
model you should have belongs_to: ticket_category, class_name: "Admin::TicketCategory
.
This should be sufficient to make it work