【发布时间】:2015-07-26 04:28:55
【问题描述】:
我有几个使用 has_one through 嵌套关系的 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。我试过使用回调,但没有成功,有人知道我如何制造这些模型和关系吗?
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) } 并创建所有正确的关系。
【问题讨论】:
标签: ruby-on-rails unit-testing rspec tdd factory-bot