工厂女孩嵌套协会

Factory Girl Nested Associations

我有几个 Rails 模型使用 has_one 嵌套关系,无论我如何构建我的 FactoryGirl 工厂,我都无法正确设置关系。

型号

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

无论我如何构建我的工厂,我似乎最终得到的用户计划不等于其订阅计划,或者由于 "it goes through more than one other association",我无法设置 usage_limit。我试过使用回调但没有成功,有人知道我如何制造这些模型和关系吗?

FactoryGirl.define do
    factory :plan do
        name                    "Test Plan 1"
        price                   19.99
        active                  true
        usage_limit
    end


FactoryGirl.define do
    factory :subscription do
        active_subscription     true
        on_trial_period         false
        coupon_used             false
        free_account            false
        plan
        user

        after(:create) do |s|
            s.user.subscription = s
            # s.user.plan = s.plan
        end
    end
end

FactoryGirl.define do
    factory :usage_limit do
        keywords_per_month      2
        discoveries_per_month   2
        keywords_per_discovery  5
    end
end

FactoryGirl.define do
    factory :user do
        email                  "user@example.com"
        password               "password"
        password_confirmation  "password"
        plan

        after(:create) do |user|
          # user.subscription = FactoryGirl.build(:subscription, :user => user, :plan => user.plan)
          # user.usage_limit = user.plan.usage_limit
        end
    end
end

我希望能够 let!(:user) { FactoryGirl.build(:user) } 并创建所有正确的关系。

FactoryGirl.build 不会持久保存到数据库中。您可能需要 FactoryGirl.create.

您需要 create 而不是 build。这应该有效:

FactoryGirl.define do
  factory :user do
    after(:create) do |user|
      user.subscription = FactoryGirl.create(:subscription)
    end
  end

  factory :plan do
    usage_limit
  end

  factory :subscription do
    plan
  end

  factory :usage_limit do
  end
end

require 'rails_helper'

describe User do
  let(:user) { FactoryGirl.create(:user) }

  it "has a subscription" do
    expect(user.subscription).to_not be_nil
  end

  it "has a plan" do
    expect(user.plan).to_not be_nil
    expect(user.plan).to eq user.subscription.plan
  end

  it "has a usage limit" do
    expect(user.usage_limit).to_not be_nil
    expect(user.usage_limit).to eq user.plan.usage_limit
  end

end