Factory Girl - 为什么记录不断被创造?
我是工厂女孩的新手。我想做的是创建 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
....
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
....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为 Factory.create(:user...) 创建了 1 个用户(您有其中两个,所以那里有两个用户)。创建两个新的 Factory.create(:permissions) 还会根据您在定义(您的关联)中设置的规则创建一个用户,因此等于 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