ruby on rails - Factory Girl Nested Associations -
i have several rails models nested relationship using has_one through, , no matter how seem structure factorygirl factories can't relationship correctly setup.
models
class user < activerecord::base has_one :subscription has_one :plan, through: :subscription has_one :usage_limit, through: :plan end class subscription < activerecord::base belongs_to :plan belongs_to :user end class plan < activerecord::base has_many :subscriptions belongs_to :usage_limit has_many :users, through: :subscriptions end class usagelimit < activerecord::base has_one :plan end no matter how structure factories, seem end users plan not being equal subscription plan, or can't setup usage_limit due "it goes through more 1 other association". i've tried using callbacks no luck, got idea how can factory these models , relationships?
factorygirl.define factory :plan name "test plan 1" price 19.99 active true usage_limit end factorygirl.define factory :subscription active_subscription true on_trial_period false coupon_used false free_account false plan user after(:create) |s| s.user.subscription = s # s.user.plan = s.plan end end end factorygirl.define factory :usage_limit keywords_per_month 2 discoveries_per_month 2 keywords_per_discovery 5 end end factorygirl.define factory :user email "user@example.com" password "password" password_confirmation "password" plan after(:create) |user| # user.subscription = factorygirl.build(:subscription, :user => user, :plan => user.plan) # user.usage_limit = user.plan.usage_limit end end end i'd able let!(:user) { factorygirl.build(:user) } , have of correct relationships created.
you need create instead of build. should work:
factorygirl.define factory :user after(:create) |user| user.subscription = factorygirl.create(:subscription) end end factory :plan usage_limit end factory :subscription plan end factory :usage_limit end end require 'rails_helper' describe user let(:user) { factorygirl.create(:user) } "has subscription" expect(user.subscription).to_not be_nil end "has plan" expect(user.plan).to_not be_nil expect(user.plan).to eq user.subscription.plan end "has usage limit" expect(user.usage_limit).to_not be_nil expect(user.usage_limit).to eq user.plan.usage_limit end end
Comments
Post a Comment