---
title: "Test factories first"
description:
  "Before running any tests make sure that all factories are running ok."
canonical_url: "https://www.bigbinary.com/blog/test-factories-first"
markdown_url: "https://www.bigbinary.com/blog/test-factories-first.md"
---

# Test factories first

Before running any tests make sure that all factories are running ok.

- Author: Neeraj Singh
- Published: October 10, 2012
- Categories: Rails

In
[blog](http://robots.thoughtbot.com/post/30994874643/testing-your-factories-first)
thoughtbot team outlined how they test their factories first. I like this
approach. Since we prefer using minitest here is how we implemented it. It is
similar to how the thoughtbot blog has described. However I still want to blog
about it so that in our other projects we can use similar approach.

First under `spec` directory create a file called `factories_spec.rb` . Here is
how our file looks.

```ruby
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe FactoryGirl do
  EXCEPTIONS = %w(base_address base_batch bad_shipping_address shipping_method_rate bad_billing_address)
  FactoryGirl.factories.each do |factory|
    next if EXCEPTIONS.include?(factory.name.to_s)
    describe "The #{factory.name} factory" do

      it 'is valid' do
        instance = build(factory.name)
        instance.must_be :valid?
      end
    end
  end
end
```

Next I need to tell rake to always run this test file first.

When rake command is executed then it goes through all the `.rake` and loads
them. So all we need to do is to create a rake file called `factory.rake` and
put this file under `lib/tasks` .

```ruby
desc 'Run factory specs.'
Rake::TestTask.new(:factory_specs) do |t|
  t.pattern = './spec/factories_spec.rb'
end

task test: :factory_specs
```

Here a dependency is being added to `test` . And if factory test fails then
dependency is not met and the main test suite will not run.

That's it. Now each unit test does not need to test factory first. All factories
are getting tested here.

## Links

- [Human page](https://www.bigbinary.com/blog/test-factories-first)
