Search code examples
ruby-on-railsfactory-botrspec-rails

Factory not registered: user (ArgumentError) when declaring variable for factorygirl.create(:user) in another factory


Here is a piece of confusion for me right here:

I have a factory for users as:

FactoryGirl.define do
  factory :user do
    email     { Faker::Internet.email }
    password  { Faker::Internet.password }
    name      { Faker::Name.name }
  end

end

and then, I am trying to create a user in another factory definition as follow:

FactoryGirl.define do
  user = FactoryGirl.create(:user)
  factory :order do
    user                  { user }
    status                1
    delivery_preferences  { "#{Faker::Address.street_address}, #{Faker::Address.city}." }
    instant_delivery      false
    status_changes        ["#{rand(5)}, #{Time.now}"]
    order_products_ids    { user.cart.order_products_ids[0..rand(3)] }
  end

end

but I keep getting an error that:

Factory not registered: user (ArgumentError)

I definitely am doing something wrong, but I really can't see it. I need some extra pair of eyes here, haha. What could be the issue here?


Solution

  • You're declaring the association improperly - using user = FactoryGirl.create(:user) basically does not work since the user factory is not guaranteed to be declared when you are defining your factory.

    Also even if this works than all the factories would share the same User record since the variable is created in scope of the factory definition - not the block which is run when FG initializes a record.

    This is how you would declare the association:

    FactoryGirl.define do
      factory :order do
        user # FactoryGirl does lazy loading when the factory is used
        status                1
        delivery_preferences  { "#{Faker::Address.street_address}, #{Faker::Address.city}." }
        instant_delivery      false
        status_changes        ["#{rand(5)}, #{Time.now}"]
        order_products_ids    { user.cart.order_products_ids[0..rand(3)] }
      end
    end