Search code examples
ruby-on-railsfactory-botrspec-rails

Get Errors From FactoryGirl.lint


I inherited a number of FactoryGirl factories that don't really work and I'm trying to bring them up to snuff. Part of that has been the use of FactoryGirl.lint. So far, however, I have been able to find which factories fail and, for any individual one, run

x = FactoryGirl.build :invalid_factory
x.valid? # returns false as expected
x.errors # prints out the validation errors for that object

What I'd like to do is avoid having to do that for each factory. Is there a way to quickly get FactoryGirl.lint to write out the errors which each invalid factory? A flag to pass, a parameter to set? The documentation is extremely sparse on .lint


Solution

  • Loop through FactoryGirl.factories to perform your check on each factory.

    FactoryGirl.factories.map(&:name).each do |factory_name|
        describe "#{factory_name} factory" do
    
          # Test each factory
          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("\n") }
            end
          end
    

    This script from the FactoryGirl wiki shows how to automate the check with RSpec and use Guard to always verify factories are valid.