Setting up FactoryGirl with Rails - marklocklear/railsgirls GitHub Wiki

Tell RSpec to use FactoryGirl

The first thing you have to do is inform RSpec that it will be using FactoryGirl as opposed to traditional Rails fixtures. You do this in spec/spec_helper.rb. The spec_helper.rb file is where you do all of your configuration for RSpec.

Open spec/spec_helper.rb and somewhere around line 20 you will see the configuration setting that applies to ActiveRecord fixtures. Change the lines to look like this:

# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.include FactoryGirl::Syntax::Methods

You now have access to all of your FactoryGirl syntax methods from within your specs.

Create Ideas Factories

FactoryGirl brings a lot of powerful features into your testing environment. We will add to them as we go through the class. For now, you just need to add a basic Idea factory for use in your upcoming Specs.

Create a new folder in spec called factories. Create a new file within the factories folder called ideas.rb. Add the following to ideas.rb:

# add to spec/factories/ideas.rb
FactoryGirl.define do
  factory :idea do
    description "My Description"
    name        "My Name"
  end
end

Create Ideas Model Spec

Normally all of your specs will be created automatically using the Rails generator. However, since we have already created our Ideas model, we will need to create the Spec manually.

Create a new folder in spec called models. Create a new file within the factories folder called idea_spec.rb. Add the following to idea_spec.rb:

# add to spec/models/idea_spec.rb
require 'spec_helper'

describe "creating Factory instances" do
  it "should succeed creating a new :idea from the Factory" do
    lambda { create(:idea) }.should_not raise_error
  end

  it "should be an instance of Idea" do
    create(:idea).class.should == Idea
    create(:idea).should be_a_kind_of Idea
  end

  it "should be a valid Idea" do
    create(:idea).valid?.should be true
    create(:idea).should be_valid
  end
end

Run the Specs

Run the specs to make sure that all of your Factories are working as expected

rspec 

You should see output that looks something like this:

Idea
  creating Factory instances
    should be a valid Idea
    should be an instance of Idea
    should succeed creating a new :idea from the Factory

Finished in 0.16775 seconds
3 examples, 0 failures

Yes! You have passing specs.