Save! modifies object

8 views
Skip to first unread message

Bruno Pinto

unread,
Apr 4, 2012, 1:28:05 AM4/4/12
to factory_girl
Hi guys,

I'm facing a problem when modifying a object while saving. From what
I've seen on factory_girl code, when you use FactoryGirl.create, it
calls model.save! but it just ignores (using tap) any modification
done on save!:

[3] pry(main)> FactoryGirl.build(:publisher)
=> {"name"=>"publisher_2"}

[4] pry(main)> FactoryGirl.build(:publisher).save
=> {"name"=>"publisher_3", "identifier"=>"4f7bda45a633100f890001c0"}

[5] pry(main)> FactoryGirl.build(:publisher).save!
#<Client::Publisher identifier="4f7bda47a633100f890001c1"
name="publisher_4"> #puts inside method save!
=> {"name"=>"publisher_4", "identifier"=>"4f7bda47a633100f890001c1"}

[6] pry(main)> FactoryGirl.create(:publisher)
#<Client::Publisher identifier="4f7bda4fa633100f890001c2"
name="publisher_5"> #puts inside method save!
=> {"name"=>"publisher_5"}

Have I missed something? As FactoryGirl.create returns an instance of
that class, I expected it to return the saved object.

Joe Ferris

unread,
Apr 17, 2012, 6:15:12 PM4/17/12
to factor...@googlegroups.com
The create strategy currently assumes that create! mutates the object to save it, which means that changes get lost if you're not mutating. It basically does this:

    instance = Model.new
    instance.some_attribute = "value"
    instance.save!
    instance

Because the return value of the to_create block (which just calls save! by default) is ignored, you need to mutate in create!.

This is arguably a bug, but fixing it would be a backwards-incompatible change in the API. We'll discuss internally how to handle this, but we're open to feedback in the meantime.

Thanks,
-Joe


--
Individuals over processes. Interactions over tools. Agile Rails training from thoughtbot, the makers of Clearance, Shoulda, & Factory Girl:
http://thoughtbot.com/services/training

You received this message because you are subscribed to the "factory_girl" mailing list.
To post to this group, send email to factor...@googlegroups.com
To unsubscribe from this group, send email to
factory_girl...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/factory_girl?hl=en

Reply all
Reply to author
Forward
0 new messages