ruby-on-rails – 工厂女孩 – 有许多协会

我正在使用工厂女孩与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)?

有任何想法吗?谢谢

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

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看到很多示例工厂

相关文章
相关标签/搜索