Auto Generate Factories for your Models

My good friend and colleague DS filled me in on a little trick that I’d like to share. When testing, it’s a good idea to have factories written for each model. Now, if your model is already created, you’ll have to spin up that factory manually. But how about ensuring your factories are created with each new model you generate?

Enters this nifty bit of code you can add to your config/application.rb file, within the Application class:

config.generators do |g|
        g.test_framework :rspec,
        :fixtures => true, # generate a factory for each model
        :view_specs => false, # do not generate view specs
        :helper_specs => false, # do not generate specs for the helper files
        :routing_specs => false, # do not generate a spec for routes
        :controller_specs => true, # generate controller specs
        :request_specs => true # generate request specs
        g.fixture_replacement :factory_girl, :dir => "spec/factories" # tells Rails to generate factories instead of fixtures

It’s the below lines of code that are configuring rails to create factories for new models.

:fixtures => true, # generate a factory for each model
g.fixture_replacement :factory_girl, :dir => "spec/factories"

Now, any time you generate a new model using the terminal, a factory will be created for that model. Just be sure to have the factory_girl and rspec gems installed in your application. Also, note that with the above code, the fixtures rails used to generate for you will no longer be created. Rather, your spec/factories directory will be populated with those helpful factory_girl factories, which in my opinion are used more widely that the out of the box rails testing fixtures.

Be sure to explore the other configurations in the included code block as well. They enable you to specify if you’d like specs for views, helpers, routes, and controllers to be created on they fly during each of those elements’ generation process.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: