Forum: RSpec create_<association?>

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Denis H. (Guest)
on 2009-05-27 17:11
(Received via mailing list)
Any know issues with the dynamic create_<association> method and
factory_girl?

I have an object created by a factory:

    @order = Factory.create :payable_order_with_line_items

and then I do:

    @order.create_ship_address(<attributes for ship_address)

then the ship_address object is persisted but the association is not
made (e.g. @order.ship_address_id is nil).

If I instead create the Address object and then say
@order.update_attributes(:ship_address => address), everything is fine.

Is this some issue with mixing factory-created objects with non?  I
can't imagine that's an issue...

Thanks,

dwh
Zach D. (Guest)
on 2009-05-28 10:41
(Received via mailing list)
On Wed, May 27, 2009 at 8:51 AM, Denis H. <removed_email_address@domain.invalid>
wrote:
>
> then the ship_address object is persisted but the association is not made
> (e.g. @order.ship_address_id is nil).
>
> If I instead create the Address object and then say
> @order.update_attributes(:ship_address => address), everything is fine.
>
> Is this some issue with mixing factory-created objects with non?  I can't
> imagine that's an issue...

I don't think it's an issue w/FactoryGirl. A belongs_to association in
Rails adds the create_xxxxx association method, which returns a new
object of the associated type that has been instantiated and saved. It
does NOT save the receiver. For example:

   @order.create_ship_address

This creates a ShipAddress and it updates @order's in-memory
ship_address_id, but it does not save @order. You have to do that.
Here's the example the Rails docs gives:

    Post#create_author (similar to post.author = Author.new;
post.author.save; post.author)

Which in this example, the post is never saved, only it's in-memory
association is set, so you still need to save @order in your example.

HTH,

>
> Thanks,
>
> dwh
>
> _______________________________________________
> rspec-users mailing list
> removed_email_address@domain.invalid
> http://rubyforge.org/mailman/listinfo/rspec-users
>



--
Zach D.
http://www.continuousthinking.com (personal)
http://www.mutuallyhuman.com (hire me)
http://ideafoundry.info/behavior-driven-development (first rate BDD
training)
@zachdennis (twitter)
This topic is locked and can not be replied to.