Home > Enterprise >  FactoryBot: Multi-Level associations?
FactoryBot: Multi-Level associations?

Time:03-23

So im relatively new to factory bot, and im pulling in some modals on some older php code into rails. And I seem to be running into a problem with one specific factory creation.

Right now here is my basic factories.rb file:

FactoryBot.define do

factory :"Core/User" do
  username {"jDoe"}
end

factory :"Core/Sex" do
  title {"Unspecified"}
  abbreviation {"U"}
end

factory :"Core/Contact" do
  first_name {"John"}
  last_name {"Doe"}
  display_phone_mobile {false}
  internal {false}
  archive {false}
  "Core/Sex"
end

factory :"Core/Employee" do
  "Core/User"
  "Core/Contact"
  username {"jDoe"}
end

end

Pretty basic right now, as the schema is sort of a tangled mess. Anyways, for whatever reason everything works until I get to trying to create an "Employee" (Sidenote: I had to add Core:: to everything and had to scour SO to find out how to add that to the symbols, since they are namespaced I guess? (I know that I need to use Core::<Model> to access the models in rails fwiw)

Anyways the models are relatively complex, but the important parts are here:

Contact.rb:

  class Core::Contact < Core::BaseModel
  self.primary_key = 'id'
  has_one :employee
  belongs_to :sex

User.rb:

  class Core::User <  Core::BaseModel
  extend Core::ActiveDirectory
  self.primary_key = 'id'

  has_one :employee

Employee.rb:

class Core::Employee < Core::BaseModel
  include ActionView::Helpers::DateHelper

  self.primary_key = 'id'

  belongs_to :contact

There are tons of other dependencies to tackle...but for whatever reason the associations don't seem to pull in the contact_id when making an employee. As in it specifically complains about TinyTds::Error: Cannot insert the value NULL into column 'contact_id'

Thing is, ALL the others work just fine. IE: if I make a Contact it pulls in the "Core/Sex" fine and I manually create the "Contact" factory and specifically pull in the ID like so:

@contact = create(:"Core/Contact")
puts @contact.attributes
@employee = create(:"Core/Employee", contact_id: @contact.id)

It works!, but I dont know why the other associations get pulled in just fine? Any ideas?

CodePudding user response:

you don't need that; You just refer to the factories as a one-word thing than then the Factory constructor has a class: option on it

just move all of your factories over to standard names

factory :employee, class: "Core::Employee" do
  user { create(:user) }
  contact { create (:contact) }
  username {"jDoe"}
end

when you refer to them as factories just use the short names with symbols and let the class: option do the rest.

  • Related