铁轨上的红宝石 - 工厂女孩 - 有很多联想



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

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

相关内容

  • 没有找到相关文章

最新更新