这是我的工厂:
users.rb的
FactoryGirl.define do
sequence(:email) do |n|
"user#{n}@example.com"
end
factory :user do
email
first_name Faker::Name.first_name
last_name Faker::Name.last_name
password "password"
password_confirmation "password"
agreed_to_age_requirements true
username "testing123"
state "AL"
city_id 201
school_id 20935
handedness "Left"
customer_id { "#{rand(1000)}" }
after(:create) do |user, elevator|
user.subscriptions << FactoryGirl.create(:subscription, account_type_name: "#{elevator.account_type_name}")
user.sports << FactoryGirl.create(:sport)
user.roles << FactoryGirl.create(:role)
end
end
factory :athlete, class: "Athlete", parent: :user do
type "Athlete"
recruit_year "2016"
end
end
Subscriptions.rb
FactoryGirl.define do
factory :subscription do
trial_expiry 30.days.from_now
active true
after :create do |subscription, elevator|
account_type {create(:account_type, name: "#{elevator.account_type_name}", price: 0)}
end
end
end
AccountTypes.rb
FactoryGirl.define do
factory :account_type do
name "Legend"
price 15
trial_period_days 0
videos 20
contributors 15
end
end
以下是我的测试结果:
before :each do
@user = create(:user)
@sport_user = create(:user, sports: [])
@school_admin_role = create(:role, name: "School Admin")
@contributor_role = create(:role, name: "Contributor")
end
问题在于,当我创建第二个用户时,已经创建了与第一个用户的订阅关联的帐户类型,因此我的测试数据库中已存在相同的帐户类型。写这个的任何方式都不会发生这种情况?
答案 0 :(得分:1)
以下是我在上述评论中试图了解的内容。如果这不起作用,请告诉我,我会删除答案。
users.rb的
FactoryGirl.define do
sequence(:email) do |n|
"user#{n}@example.com"
end
factory :user do
email
first_name Faker::Name.first_name
last_name Faker::Name.last_name
password "password"
password_confirmation "password"
agreed_to_age_requirements true
username "testing123"
state "AL"
city_id 201
school_id 20935
handedness "Left"
customer_id { "#{rand(1000)}" }
subscriptions {[create(:subscription, account_type_name: "#{account_type_name}")]}
roles {[create(:role)]}
after(:create) do |user|
user.sports << FactoryGirl.create(:sport)
end
end
factory :athlete, class: "Athlete", parent: :user do
type "Athlete"
recruit_year "2016"
end
end
Subscriptions.rb
FactoryGirl.define do
factory :subscription do
trial_expiry 30.days.from_now
active true
after(:create) do |subscription, evaluator|
account_type {create(:account_type, name: "#{evaluator.account_type_name}", price: 0)}
end
end
end
AccountTypes.rb
FactoryGirl.define do
factory :account_type do
name "Legend"
price 15
trial_period_days 0
videos 20
contributors 15
end
end
以下是我的测试结果:
before :each do
@school_admin_role = create(:role, name: "School Admin")
@contributor_role = create(:role, name: "Contributor")
@user = create(:user, account_type_name: "Free")
@sport_user = create(:user, sports: [], account_type_name: "Other Free Name")
end