Separate Factory Files?

I’ve noticed that when I generate a new model in rails that factory girl creates a new file spec/factories/model_name.rb

I typically just keep all my factories in spec/factories.rb. I’ve seen others do this too.

Is there a best practice for this?

I seem to be in the minority here, but I like keeping them in separate files to avoid the getting one enormous file. I don’t think the one-big-file approach for this particular case is a huge anti-pattern, it’s just a matter of personal preference.

(I also have vim mapped so that models and model specs can jump to the right factory.)

it’s awesome, could you share it here?

Fun stuff that I have in there:

  • Related file for models is the factory rather than the schema (which I’ve never found that useful). This shortcut also lets you type Vfactory model_names! and generate a factory template.
  • Factory files can jump to the model or the model spec
  • Request specs can jump to controllers rather than trying to look in app/requests
  • I use Egemfile to get to the Gemfile because it seems more instinctual to me
  • E/V/Sroutes for routes file
  • E/V/Slocales for the English locales file (because for the moment I only use one locale file)
1 Like

Did you forget to include a link to your dotfiles perchance? :slight_smile:

@aaronmcadam, oops!

They are built to work off the Thoughtbot dotfiles, so just keep that in mind when browsing configs.

@samnang and @aaronmcadam, the relevant commands are in the rails.vim file in my dotfiles.

I don’t really see any benefit to keeping it in a single factory file. I split it up for the same reason I don’t have one really long application.js file.

To contradict myself, one major benefit I can see to having one large factory file is that when you have aliases or factories for polymorphic/STI models that result in the name of the factory not necessarily being super clear from the file, one factory file can speed up searching.