Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

ruby - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...