工厂女孩 - 为什么记录会不断创建?

时间:2011-03-20 17:46:39

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

我是工厂女孩的新手。我要做的是创建属于一个组的2个用户,通过权限模型加入。这就是我所拥有的。当我运行这个rspec时,它创建了超过2个用户,4 +。为什么?感谢

factories.rb:

require 'factory_girl'

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        "xxxxxxxx"
end

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

Factory.define :permission do |f|
  f.role_id         1
  f.user {|i| i.association(:user)}
  f.group {|i| i.association(:group)}  
  f.creator_id {|i| i.association(:user).id}
end

incoming_mails_controller_spec.rb:

describe IncomingMailsController do

  include Devise::TestHelpers

  before do
    @user = Factory.create(:user, :permissions => [Factory.create(:permission)])
    @user2 = Factory.create(:user, :permissions => [Factory.create(:permission)])  
    @group = Factory(:group)
  end


  it "should create a new IncomingMail record in the db" do
  ....
  end
....

1 个答案:

答案 0 :(得分:4)

这是因为Factory.create(:user ...)创建了一个用户(你有两个这样的用户,那就是两个用户)。并且创建两个新的Factory.create(:permissions)也会根据您在define(您的关联)中设置的规则创建用户,因此等于4。

如果您想在此处仅创建两个用户,则可以

@user = Factory.create(:user)
@user1 = Factory.create(:user)
@perm1 = Factory.create(:permission, :user => @user)
@perm2 = Factory.create(:permission, :user => @user1)