Test factories first

 
 

In this blog 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.

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 .

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

task test: :factory_specs

Here a dependecy 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.

 
Neeraj Singh's profile picture

Comments