Last Updated: February 25, 2016
·
983
· davidrhyswhite

Testing your FactoryGirl factories

Since I like to have at least two factories per model in Rails, one valid and one invalid it's a good idea to test that they both return an expected result:

So given I have a factory like this:

FactoryGirl.define do
  factory :task do
    title "A single to do item"
    description "Some more details regarding the task"
  end
  factory :invalid_task, class: "Task" do
    title ""
    description ""
  end
end

Then I can test the factories pass with a simple spec:

require 'spec_helper'
FactoryGirl.factories.map(&:name).each do |name|
  describe "the #{name} factory" do
    if name =~ /invalid/
      it 'is invalid' do
        build(name).should_not be_valid
      end
    else
      it 'is valid' do
        build(name).should be_valid
      end
    end
  end
end

1 Response
Add your response

Quite cool spec. Until now I've had a spec for that within the model spec. Thanks very much for sharing. :-)

over 1 year ago ·