Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between the build and create methods in FactoryGirl?

The Factory Girl introduction delineates the difference between FactoryGirl.build() and 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!

like image 625
Avery Avatar asked Dec 31 '12 05:12

Avery


People also ask

What is Factorybot used for?

Factory Bot is often used in testing Ruby on Rails applications; where it replaces Rails' built-in fixture mechanism. Rails' default setup uses a pre-populated database as test fixtures, which are global for the complete test suite.

What is Factorybot in Rspec?

Factory Bot is a helper for writing factories for Ruby tests. It was previously known as Factory Girl.

What is Build_stubbed?

build_stubbed is the younger, more hip sibling to build ; it instantiates and assigns attributes just like build , but that's where the similarities end.


2 Answers

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

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

e.g.

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

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

like image 124
Helio Santos Avatar answered Oct 20 '22 13:10

Helio Santos


Using FactoryGirl.build(:factory_name) does not persist to the db and does not call save!, so your Active Record validations will not run. This is much faster, but validations might be important.

Using FactoryGirl.create(:factory_name) will persist to the db and will call Active Record validations. This is obviously slower but can catch validation errors (if you care about them in your tests).

like image 42
chasm Avatar answered Oct 20 '22 13:10

chasm