Search code examples
ruby-on-railsruby-on-rails-3.2factory-botrspec-rails

How can I avoid using 'FactoryGirl.reload' due to using 'sequence' in my factories?


Having to use FactoryGirl.reload likely to put some overhead on the time it takes to run all tests (when many tests exist) and also it is described as an Anti-Pattern.

How can I keep using the sequencing for unique fields, yet test for the correct values?

You can see in my code that...

  • I have to call FactoryGirl.reload so that the increment starts at 1 in case any previous tests have already been run.

  • I have to state :count => 1 because there will only ever be one instance of that value.

spec/factories/clients.rb

FactoryGirl.define do
  factory :client do
    name                "Name"
    sequence(:email}    { |n| "email#{n}@example.com" }
    sequence(:username) { |n| "username#{n}" }
  end
end

spec/clients/index.html.erb_spec.rb

require 'spec_helper'

describe "clients/index" do
  before do
    FactoryGirl.reload
    (1..5).each do
      FactoryGirl.create(:client)
    end
    @clients = Client.all
  end

  it "renders a list of clients" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
    assert_select "tr>td", :text => "Name".to_s, :count => 5
    assert_select "tr>td", :text => "[email protected]".to_s, :count => 1
    assert_select "tr>td", :text => "username1".to_s, :count => 1
  end
end

Solution

  • How about passing in special names for this particular test?

    require 'spec_helper'
    
    describe "clients/index" do
      before do
        (1..5).each do |num|
          FactoryGirl.create(:client, username: "special#{num}")
        end
        @clients = Client.all
      end
    
      it "renders a list of clients" do
        render
        assert_select "tr>td", :text => "special1".to_s, :count => 1
      end
    end