thoughtbot / factory_bot_rails

Factory Bot ♥ Rails

Home Page:https://thoughtbot.com/services/ruby-on-rails

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

new reload behavior breaks normal code reloading with Spring

jakeonfire opened this issue · comments

Whenever I change code inside the Rails app/ dir, FactoryBot no longer reloads (per the decisions in this commit: 02a0f58). This causes a myriad of strange errors, like having multiple class objects for models for which there exist factories (in other words, MyModel.object_id, and my_model_factory_instance.class.object_id drift apart somehow), ActiveModel methods seem to be forgotten (like ActiveRecord#store_accessor not defined errors), and other weirdness.

Adding back

if defined?(Spring)
  Spring.after_fork { FactoryBot.reload }
end

fixes this issue (for example, in a config.after_initalize block in config/environments/test.rb). But this doesn't feel right at all.

I'm not sure if this has something to do with how our app is configured, but it makes using spring and factory_bot_rails 5.x (and Rails 5.2?) together a non-option (without the workaround mentioned above).

I had a feeling this was going to be a problem when I saw thoughtbot/factory_bot#1029 (comment).

We may need to swap out reloader.execute_if_updated in

reloader.execute_if_updated
with reloader.execute, so any time anything changes in the application factory_bot will reload too. This matches what the rails routes reloader does: https://github.com/rails/rails/blob/2420c44d4b1dfbffea7b624cb8a8c68beb05936f/railties/lib/rails/application/finisher.rb#L144-L154

Thanks for the issue!

I had the same thought, but doing so seems to conflict with some other aspect of the loading architecture, yielding (for me):
Factory already registered: adapter (FactoryBot::DuplicateDefinitionError)
...which is the first factory alphabetically.

The change to reloader.execute plus removing these three lines seems to fix it though:

config.after_initialize do
FactoryBot.find_definitions
end

If that sounds like a legit fix I'd be happy to open a PR. I don't understand the gem well enough to know if there's a better path.

Yup, that seems like the way to go. I would love to see a failing spec for this, but I haven't actually been able to recreate it myself.

@jakeonfire are you working on this, or are you still interested in working on this? Let me know if I can help.

@composerinteralia i am not - we are using a work-around. happy to submit a PR if you'd like, but i won't be able to figure out a failing spec for it.

@jakeonfire Feel free to submit a PR with whatever you have (although no pressure at all), and I can try and add the test coverage.

Fixed with #330

thanks for your help with this!
dancing_panda