工厂女孩 - has_many协会

时间:2011-05-14 18:14:22

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

我正在使用rspec的工厂女孩​​,这就是我所拥有的:

factories.rb

Factory.define :user do |f|
  f.sequence(:fname) { |n| "fname#{n}" }
  f.sequence(:lname) { |n| "lname#{n}" }
  f.sequence(:email) { |n| "email#{n}@google.com" }
  f.password               "password"
  f.password_confirmation { |u| u.password }
  f.invitation_code        "xxxxxxx"
end

Factory.define :group do |f|
  f.sequence(:name) { |n| "myGroup#{n}" }
  f.sequence(:private_email) { |n| "myGroup#{n}" }
end

Factory.define :permission do |f|
  f.role_id         1
end

groups_controller_spec.rb

describe GroupsController do
  include Devise::TestHelpers

  before (:each) do
    @user1 = Factory.create(:user)
    @user1.confirm!
    sign_in @user1
    @group = Factory.create(:group)
    @group2 = Factory.create(:group)
    @group3 = Factory.create(:group)
    @permission_user_1 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group)
    @permission_user_2 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group2)
    @permission_user_3 = Factory.create(:permission, :user => @user1, :creator_id => @user1.id, :group => @group3)
  end

.......

问题是组模型有一个user_id字段,它不是由工厂设置的。如何创建用户,然后让工厂代表该用户创建组。喜欢@ user1.group.factory.create(:group)?

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:15)

不要为所有用户执行此操作,而是创建从用户工厂继承的另一个工厂。

Factory.define :user_with_group, :parent => :user do |u|
  u.groups  { |g| [ g.association(:group), 
                    g.association(:group)
                  ]}
end

您可以在https://github.com/drhenner/ror_ecommerce/tree/master/spec/factories

看到许多示例工厂