FactoryGirl中的build和create方法之间有什么区别? [英] What's the difference between the build and create methods in FactoryGirl?

查看:90
本文介绍了FactoryGirl中的build和create方法之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

《工厂女郎》简介描述了 FactoryGirl.build() FactoryGirl.create():

# Returns a User instance that's not saved
user = FactoryGirl.build(:user)

# Returns a saved User instance
user = FactoryGirl.create(:user)

我仍然不了解两者之间的实际区别.有人可以举一个您想使用其中一个而不是另一个的示例吗?谢谢!

I still doesn't understand the practical differences between the two. Can someone give an example where you would want to use one and not the other? Thanks!

推荐答案

create()方法保留模型的实例,而 build()方法保留模型的实例仅在内存中.

The create() method persists the instance of the model while the build() method keeps it only on memory.

我个人而言,仅在确实需要持久性时才使用 create()方法,因为写入DB会浪费测试时间.

Personally, I use the create() method only when persistence is really necessary since writing to DB makes testing time consuming.

例如

我创建用户进行 create()身份验证,因为我的身份验证引擎查询了数据库.

I create users to authentication with create() because my authentication engine queries the DB.

要检查模型是否具有属性,请使用 build()方法,因为不需要数据库访问.

To check if a model has an attribute the build() method will do because no DB access is required.

it{Factory.build(:user).should respond_to(:name)}

更新

在建立关联时,构建实际上会创建"一个例外,即您的关联不再在内存中,而是持久存在.请记住这一点" –摇动

Update

"There is one exception that build actually 'creates' when you are building associations, i.e your association are no longer in memory but persisted. Keep that in mind" – Shakes

这篇关于FactoryGirl中的build和create方法之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆