Search code examples
ruby-on-railsrakefactory-bot

rails running code in FactoryGirl on every rake task, actually on every environment load


We could not run rake db:schema:load on a new machine because somewhere when loading the Rails environment for the rake task a class method was being called that tried to access a table in the db, which obviously did not yet exist.

I found that it was coming from a FactoryGirl definition.

For 2 of the factories we were setting a location_id variable to the world location.id like this

FactoryGirl.define do
  factory :some_model do
    ....
    ....
    cached_location_id Location.world.id
    ....
  end
end

so when rails was loading all our code, it was immediately running the Location.world. I think this is peculiar to FactoryGirl.

How to solve this?


Solution

  • So just change it to only run the Location.world code when the Factory is asked to create the model using { }s like this:

    FactoryGirl.define do factory :some_model do .... .... cached_location_id {Location.world.id } .... end end

    What a Gotchya!