Factory Girl - Why are Records being continually c

2019-06-01 19:37发布

问题:

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)