← Back to Upcase

Separate Factory Files?


(Nicolo) #1

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?


(Geoff Harcourt) #2

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.)


(Samnang Chhun) #3

it’s awesome, could you share it here?


(Geoff Harcourt) #4

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)

(Aaron Mc Adam) #5

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


(Geoff Harcourt) #6

@aaronmcadam, oops!

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


(Geoff Harcourt) #7

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


(Cyle Hunter) #8

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.


(Geoff Harcourt) #9

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.