t0r*_*edo 3 tdd rspec ruby-on-rails ruby-on-rails-3.2 factory-bot
我想使用FactoryGirl 4.2.0正确建立多对多工厂集.我一直在使用以前的FactoryGirl版本混合在一起的过时语法的文档/示例,它只是不适合我.
如何根据以下两个资源及其链接表设置此方案:
class User < ActiveRecord::Base
has_many :user_registrations
has_many :registrations, through: :user_registrations
end
class UserRegistration < ActiveRecord::Base
belongs_to :user
belongs_to :registration
end
class Registration < ActiveRecord::Base
has_many :user_registrations
has_many :users, through: :user_registrations
end
Run Code Online (Sandbox Code Playgroud)
根据此处的文档,这是我到目前为止所拥有的.这就像我到目前为止所取得的任何实际进展一样接近.
FactoryGirl.define do
factory :registration do
user
end
factory :user, class: User do
sequence(:email) { |n| "foo#{n}@example.com" }
password "password"
factory :user_with_registrations do
ignore do
registrations_count 1
end
after(:create) do |user, evaluator|
registrations FactoryGirl.create_list(:registration, evaluator.registrations_count, user: user)
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
以下列方式失败,我意识到这是因为这种设置被认为是一对多的关系.
1) User Login Success
Failure/Error: user = FactoryGirl.create(:user_with_registrations)
NoMethodError:
undefined method `user=' for #<Registration:0x007fc48e2ca768>
# ./spec/factories.rb:18:in `block (4 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)
使用最新的FactoryGirl语法为多对多场景定义工厂集的正确方法是什么?(4.2.0)
谢谢!
小智 6
对我来说,看起来你必须通过和完成has_many
关联.这看起来就像Registrations
Users
UserRegistrations
factory :user_registration do
association :user
association :registration
end
factory :user do
..setup for email and password
factory :user_with_registrations do
ignore do
registrations_count 1
end
after(:create) do |user, evaluator|
FactoryGirl.create_list(:user_registration, evaluator.registrations_count, user: user)
end
end
end
factory :registration do
..setup for registration
factory :registration_with_user do
ignore do
users_count 1
end
after(:create) do |registration, evaluator|
FactoryGirl.create_list(:user_registration, evaluator.users_count, registration: registration)
end
end
end
Run Code Online (Sandbox Code Playgroud)