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
786 views
in Technique[技术] by (71.8m points)

ruby on rails - has_many while respecting build strategy in factory_girl

Situation

# Models
class User < ActiveRecord::Base
  has_many :items 
end 

class Items < ActiveRecord::Base
  belongs_to :user 
  validates_presence_of :user_id 
end 

# Factories
Factory.define(:user) do |u| 
  u.name "foo" 
end 

Factory.define(:user_with_items, :parent => :user) do |u| 
  u.items {|items| [items.association(:item), items.association(:item)]} 
end

Factory.define(:item) do |i| 
  i.color "red" 
end 

Factory.define(:item_with_user, :parent => :user) do |i| 
  i.association(:user) 
end

Problem

If you run @user = Factory(:user_with_items) then @user.items contains the two items. The issue is that the items aren't associated with the user in the database. If you reload the association @user.items(true) then you get back an empty array. I know you can build them manually or create helper methods on your own to build the object graph, but I'd like to avoid that.

Question

So, my question is how can you build up a has_many relationship in factory_girl while respecting the build strategy?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I wrote it properly with inheritance and all that. My commits are merged in here and here.

It's now in FactoryGirl 1.2.3, woot!


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

...