Skip to content

Testing all Factories (with RSpec)

Ben Linton edited this page Jul 11, 2014 · 27 revisions

To make sure that your factories are valid you can automatically test all of them with the following code:

# require `spec_helper` instead if using RSpec 2.x or you're not using rails
require 'rails_helper' 

# If using RSpec 2.x, you can remove the `RSpec.` from `describe`
RSpec.describe "Factory Girl" do
  FactoryGirl.factories.map(&:name).each do |factory_name|
    describe "#{factory_name} factory" do

      it "is valid" do
        factory = FactoryGirl.build(factory_name)
        if factory.respond_to?(:valid?)
          # the lamba syntax only works with rspec 2.14 or newer;  for earlier versions, you have to call #valid? before calling the matcher, otherwise the errors will be empty
          expect(factory).to be_valid, lambda { factory.errors.full_messages.join(',') }
        end
      end

      FactoryGirl.factories[factory_name].definition.defined_traits.map(&:name).each do |trait_name|
        context "with trait #{trait_name}" do
          it "is valid" do
            factory = FactoryGirl.build(factory_name, trait_name)
            if factory.respond_to?(:valid?)
              expect(factory).to be_valid, lambda { factory.errors.full_messages.join(',') }
            end
          end
        end
      end

    end
  end
end