Wednesday, February 10, 2010

Factory Girl has many associations gotcha

Suppose Post has many Items

class Post < ActiveRecord::Base
has_many :items
end

class Item < ActiveRecord::Base
belongs_to :post
end

When setting up data for tests using factory girl

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

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 @post.id. Instead do this.

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

No comments: