2

我的 factory.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”的学校。

我认为 factory.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
4

2 回答 2

2

这条线创建了第一所学校

school = FactoryGirl.create(:school)

这是第二个:

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

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

user = FactoryGirl.create(:user, :username => "jdoe", :school => school)
于 2012-12-31T23:39:22.390 回答
0

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

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

# 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

于 2012-12-31T22:54:59.800 回答