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

微笑、不失礼 提交于 2019-12-25 03:21:50

问题


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 => "email1@example.com".to_s, :count => 1
    assert_select "tr>td", :text => "username1".to_s, :count => 1
  end
end

回答1:


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



回答2:


Adding to mind.blank's answer... If you then wish to test the incremented values, place them inside an incremental loop as well.

  it "renders a list of clients" do
    render
    (1..5).each do |num|
      assert_select "tr>td", :text => "special#{num}".to_s, :count => 1
    end
  end


来源:https://stackoverflow.com/questions/16049443/how-can-i-avoid-using-factorygirl-reload-due-to-using-sequence-in-my-factori

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!