Wednesday, February 10, 2010

Factory Girl has many associations gotcha

Suppose Post has many Items

class Post < ActiveRecord::Base
has_many :items

class Item < ActiveRecord::Base
belongs_to :post

When setting up data for tests using factory girl

Factory.define :item do {|p| p.association(:post)}

Don't do this!

@post.items << Factory(:item)

Factory will create an item with another post_id and this will not be automatically changed to Instead do this.

Factory(:item, :post => @post)

No comments: