Factory Girl:如何在不创建新记录的情况下将记录与另一条记录相关联?

时间:2010-10-26 19:07:28

标签: ruby-on-rails factory-bot rspec2

我正在使用Factory Girl / Rspec2 / Rails 3。

factories.rb 中,我有:

Factory.define :user do |user|
  user.name       'Some guy'
  user.email      'some_guy@somewhere.org'
  user.password   'password'
end

Factory.define :org_admin, :parent => :user do |user|
  user.email 'org_admin@somehwere.org'
end

Factory.define :user_with_membership_request, :parent => :user do |user|
  user.email 'user_with_membership_request@somehwere.org'
end

Factory.define :organization do |org|
  org.name        'MEC'
  org.description 'Mountain Equipment Co-op'
end

Factory.define :membership do |membership|
  membership.user { Factory(:user) }
  membership.organization { Factory(:organization) }
end

Factory.define :admin_membership, :parent => :membership do |membership|
  membership.user { Factory(:org_admin) }
  membership.is_admin true
  membership.status 'active'
end

Factory.define :membership_request, :parent => :membership do |membership|
  membership.user { Factory(:user_with_membership_request) }
  membership.status 'requested'
end

然后在我的rspec测试中我有:

  it 'should accept the membership request' do
    @org_admin = Factory(:org_admin)
    test_sign_in(@org_admin)
    @organization = Factory(:organization)
    @membership_request = Factory(:membership_request)

    put :update, :organization_id => @organization.id, :id => @membership_request.id, :acceptance => 'approve'
    ...
  end

当我进行测试时,我得到:

 Failure/Error: @membership_request = Factory(:membership_request)
 Validation failed: Name has already been taken

我理解失败的原因是因为FactoryGirl正在创建另一个组织(同名)。

但我想做的是创建几个与同一组织相关的成员资格。我该怎么做?

感谢。

肖恩

3 个答案:

答案 0 :(得分:19)

您可以检查现有组织并使用它,或者如果不存在则创建一个:

Factory.define :membership do |membership|
  membership.user { Factory(:user) }
  membership.organization { Organization.first || Factory(:organization) }
end

FactoryGirl 4+更新:

Factory.define do
  factory :membership do
    user { create(:user) }
    organization { Organization.first || create(:organization) }
  end
end

另一种方法是为要重复使用的每个工厂使用唯一标识符(例如:名称),然后使用initialize_with生成它:

factory :organization_1 do
  ignore { organization_name 'Sample Organization 1' }
  name { organization_name }
  initialize_with { Organization.find_or_create_by_name(organization_name) }
end

现在,对:organization_1的任何引用都将始终检索相同的Organization。显然,您必须使用不同的名称才能工作。

答案 1 :(得分:4)

有两件事。 1.您可能仍希望为Factory(:organisation)创建唯一的名称,您可以使用Factory.sequence来实现该名称,这将为您创建唯一的名称。 2.您可以传入Factory(:membership_request, :organization => @organization)以使用现有对象而不是创建新对象。

答案 2 :(得分:2)

使用mongoid,您可以结合使用#find_or_create_by方法和Factory.attributes_for并执行类似的操作

factory :membership do
    organization { Organization.find_or_create_by(Factory.attributes_for(:organization))}
end

我确定ActiveRecord有类似的东西。