In 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.
1require File.expand_path(File.dirname(__FILE__) + '/spec_helper') 2 3describe FactoryGirl do 4 EXCEPTIONS = %w(base_address base_batch bad_shipping_address shipping_method_rate bad_billing_address) 5 FactoryGirl.factories.each do |factory| 6 next if EXCEPTIONS.include?(factory.name.to_s) 7 describe "The #{factory.name} factory" do 8 9 it 'is valid' do 10 instance = build(factory.name) 11 instance.must_be :valid? 12 end 13 end 14 end 15end
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 .
1desc 'Run factory specs.' 2Rake::TestTask.new(:factory_specs) do |t| 3 t.pattern = './spec/factories_spec.rb' 4end 5 6task 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.