【发布时间】:2013-07-15 20:34:23
【问题描述】:
我想使用 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
这是我目前所拥有的,根据文档found here。这与我迄今为止取得的任何实际进展一样接近。
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
以下方式失败,我意识到这是因为此设置用于一对多关系。
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)>'
使用最新的 FactoryGirl 语法为多对多场景定义工厂集的正确方法是什么? (4.2.0)
谢谢!
【问题讨论】:
标签: ruby-on-rails rspec ruby-on-rails-3.2 tdd factory-bot