Factory Girl - Why are Records being continually created?

╄→гoц情女王★ 提交于 2019-12-23 01:45:42

问题


I'm new to factory girl. What I'm trying to do is create 2 users, which belong to a group, joined by the permission model. Here's what I have. When I run this one rspec, it creates more than 2 users, 4+. Why? thanks

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:


This is because Factory.create(:user...) creates 1 one user (you have two of these, so thats two users right there). And creating two new Factory.create(:permissions) also creates a user by the rules you set up in your define(your associations), thus equaling 4.

If you wanted to to only create two users here, you could do

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


来源:https://stackoverflow.com/questions/5370266/factory-girl-why-are-records-being-continually-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!