工厂女孩何时在db中创建对象? [英] when does factory girl create objects in db?
问题描述
我正在尝试使用FactoryGirl
/shoulda
模拟会话(它与固定装置一起工作,但是在使用工厂时遇到了问题).我有以下工厂(用户登录名和电子邮件均具有unique
验证):
I am trying to simulate a session using FactoryGirl
/shoulda
(it worked with fixtures but i am having problems with using factories). I have following factories (user login and email both have unique
validations):
Factory.define :user do |u|
u.login 'quentin'
u.email 'quentin@example.com'
end
Factory.define :session_user, :class => Session do |ses|
ses.association :user, :factory => :user
ses.session_id 'session_user'
end
这是测试
class MessagesControllerTest < ActionController::TestCase
context "normal user" do
setup do
@request.session[:user_id]=Factory(:user).id
@request.session[:session_id]=Factory(:session_user).session_id
end
should "be able to access new message creation" do
get :new
assert_response :success
end
end
end
但是当我运行rake test:functionals
时,我得到了这个测试结果
but when i run rake test:functionals
, I get this test result
1) Error:
test: normal user should be able to access new message creation. (MessagesControllerTest):
ActiveRecord::RecordInvalid: Validation failed: Account name already exists!, Email already exists!
这意味着当我在测试设置中引用记录时,该记录已存在于db中.这里有我不懂的东西吗? FactoryGirl
在启动时如何在db中创建所有工厂?
which means that record already exists in db when I am referring to it in the test setup. Is there something I don't understand here? does FactoryGirl
create all factories in db on startup?
rails 2.3.5/shoulda/FactoryGirl
rails 2.3.5/shoulda/FactoryGirl
推荐答案
Factory(:user)
是Factory.create(:user)
的快捷方式,因此在您的设置中,您将创建两个对象并将其保存到数据库中.
Factory(:user)
is a shortcut for Factory.create(:user)
so within your setup you are creating two objects and saving them to the database.
Factory.build(:user)
将为您创建一个user
记录,而不会将其保存到数据库中.
Factory.build(:user)
will create you a user
record without saving it to the DB.
编辑
在您的session_user
工厂中,您正在创建一个用户,然后在测试设置中创建另一个用户. FactoryGirl
将创建新的user
记录,因为您在session_user
工厂中具有关联.
Within your session_user
factory you are creating a user and then creating another within your test setup. FactoryGirl
will create a new user
record because you have the association in the session_user
factory.
您可以从session_user
对象获取您的user
实例,如下所示:-
You can either get your user
instance from the session_user
object as follows :-
context "normal user" do
setup do
session = Factory(:session_user)
@request.session[:session_id] = session.session_id
@request.session[:user_id] = session.user_id
end
,或者您可以向user
工厂添加一些详细信息,以确保唯一的名称和电子邮件地址,如下所示:-
or you can add some details to the user
factory to ensure unique name and email addresses as follows :-
Factory.define :user do |u|
u.sequence(:login) {|n| "quentin#{n}" }
u.sequence(:email) {|n| "quentin#{n}@example.com"}
end
这篇关于工厂女孩何时在db中创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!