cjn6dg
Last Updated: February 25, 2016
·
799
· davidrhyswhite
8d66c15905e6a8cfc1ce63c81cdfc531

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
Say Thanks
Respond

1 Response
Add your response

3472
2aaae7041aca85da930bcaf14d6768d2

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 ·