factory girl multiple has_many through's

一世执手 提交于 2019-12-21 04:49:07

问题


I need to create some factories that are made of multiple has many through's

Here are my models

Topic
  has_many :plan_topics
  has_many :plans, :through => :plan_topics

PlanTopic
  belongs_to :plan
  belongs_to :topic

Plan
  has_many :subscriptions
  has_many :members, :through => :subscriptions
  has_many :plan_topics
  has_many :topics, :through => :plan_topics

Subscription
  belongs_to :member
  belongs_to :plan

Member
  has_many :subscriptions
  has_many :plans, :through => :subscriptions

Here is what I have

Factory.define :topic do |topic|
  topic.name "Operations"
end

Factory.define :plan do |plan|
  plan.title "A test Finance plan"
  plan.price "200"
end

Factory.define :plan_topic do |plan_topic|
  plan_topic.topic {|topic| topic.association(:topic)}
  plan_topic.plan {|plan| plan.association(:plan)}
end

What I would like to do is this - Factory(:member_with_subscription)

Factory.define :member_with_subscription do |subscription|
  subscription.association(:plan_with_topic)
  subscription.association(:member)
end

Is there a way of doing this ?


回答1:


Consider using after_build callback to set all required dependencies. For example:

Factory.define :member_with_subscription, :class => 'Member' do |m|
  m.after_build do |member|
    member.subscriptions << Factory.build(:subscription)
  end
end



回答2:


I do it slightly differently, and this way might be slightly easier to understand:

FactoryGirl.define do
  factory :member_with_description do
    after(:build) do |member|
      member.subscriptions << FactoryGirl.build(:subscription)
    end
  end 
end


来源:https://stackoverflow.com/questions/8259074/factory-girl-multiple-has-many-throughs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!