本文介绍了工厂女孩-为什么要连续创建记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是工厂女孩的新手.我想要做的是创建2个用户,这些用户属于一个组,并由权限模型加入.这就是我所拥有的.当我运行一个rspec时,它将创建2个以上的4个以上的用户.为什么?谢谢

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
....

推荐答案

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

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)

这篇关于工厂女孩-为什么要连续创建记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 00:16