我有几个使用has_one的嵌套关系的Rails模型,无论我如何构建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
无论我如何构建我的工厂,我似乎最终得出的用户计划不等于其订阅计划,或者我无法设置usage_limit,因为&#34;它经历了不止一个其他协会&#34;。我试过使用回调没有运气,任何人都知道如何制作这些模型和关系?
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) }
并创建所有正确的关系。
答案 0 :(得分:4)
您需要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
答案 1 :(得分:2)
FactoryGirl.build
不会持久存储到数据库中。您可能需要FactoryGirl.create
。