Rails FactoryGirl Duplicated Factory

时间:2012-12-31 22:45:25

标签: ruby-on-rails-3 rspec factory-bot

我在factories.rb文件中定义了以下工厂:

require 'factory_girl'

FactoryGirl.define do
    sequence(:email) {|n| "person-#{n}@example.com" }

    factory :country do
        ...
    end
    factory :state do
        country
        ...
    end
    factory :school do
        name "Test School"
        country
        state
    end
    factory :user do
        school
        email
        ... 
    end
end

在rspec中测试时,在我的一个描述符中调用FactoryGirl.create(:school)会导致创建两个名为“Test School”的学校。

我认为在factories.rb中定义的工厂只是一堆未保存的实例对象,有人可以澄清为什么我遇到这个问题吗?

这是确切的rspec:

require 'spec_helper'
describe "school login" do
  it "displays a success message upon successful login to school",do  
    school = FactoryGirl.create(:school)
    user = FactoryGirl.create(:user, :username => "jdoe")
    School.all.each do |school|
      puts school.name #2x => "Test School"
    end
    visit school_path(user.school)
    click_link('login')
    fill_in "username", :with => "jdoe"
    fill_in "password", :with => "secret"
    click_button "Sign in"
    expect(page).to have_selector(".alert-success")
  end
end

2 个答案:

答案 0 :(得分:2)

这一行创建了第一所学校

school = FactoryGirl.create(:school)

这是第二个:

user = FactoryGirl.create(:user, :username => "jdoe")

这是因为在您的用户工厂中您定义了每个用户都应该有一所学校,因此FactoryGirl正在为您创建它。如果您希望您的用户与第一所学校相关联,您可以执行以下操作:

user = FactoryGirl.create(:user, :username => "jdoe", :school => school)

答案 1 :(得分:0)

上下文代码是什么?你是如何发现有2 schools创建的?

在声明create(:object)build(:object)之前,用ruby文件(工厂)编写的代码既不会保存到数据库,也不会创建为对象。

# Returns a User instance that's not saved
user = FactoryGirl.build(:user)

# Returns a saved User instance
user = FactoryGirl.create(:user)

有关详细信息,请参阅:https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#using-factories