以下是关联设置:
我想在类别级别生成记录,并指定章节数,页数和可选的文本或音频记录。
我知道使用create_list指定第一级关联(章节)。有没有办法指定更深层关联的计数?最初的想法告诉我嵌套after(:create)。这是正确的方法吗?
FactoryGirl.define do
factory :category do
ignore do
chapters_count 1
end
trait :with_chapters do
after(:create) do |instance, evaluator|
create_list :chapter, evaluator.chapters_count, category: instance
end
end
trait :with_chapters_and_pages do
...?
end
trait :with_chapters_and_pages_with_text do
...?
end
trait :with_chapters_and_pages_with_audio do
...?
end
end
end
在使用FactoryGirl并阅读语法/ methods.rb代码之后,我想出了一个可行的解决方案。如果其他人有更好的方法,请分享:)
# category_factory.rb
FactoryGirl.define do
# Fields
# --------------------------------------------------
(...)
# Transient Attributes
# --------------------------------------------------
ignore do
chapter_count 1 # Number of associated Chapters to create
page_count 1 # Number of Chapter associated Pages to create
page_type :with_text # Page type either :with_text (default) or :with_audio
end
# Traits
# --------------------------------------------------
trait :with_chapter do
after(:create) do |instance, evaluator|
create_list :chapter, evaluator.chapter_count, category: instance
end
end
trait :with_chapter_and_page do
after(:create) do |instance, evaluator|
create_list :chapter, evaluator.chapter_count, :with_page, category: instance, page_count: evaluator.page_count, page_type: evaluator.page_type
end
end
end
# chapter_factory.rb
FactoryGirl.define do
# Fields
# --------------------------------------------------
(...)
category
# Transient Attributes
# --------------------------------------------------
ignore do
page_count 1 # Number of Chapter associated pages to create
page_type :with_text # Page type either :with_text (default) or :with_audio
end
# Traits
# --------------------------------------------------
trait :with_page do
after(:create) do |instance, evaluator|
create_list :page, evaluator.page_count, evaluator.page_type, chapter: instance
end
end
end
# page_factory.rb
FactoryGirl.define do
# Fields
# --------------------------------------------------
(...)
chapter
# Traits
# --------------------------------------------------
trait :with_text do
after(:create) do |instance, evaluator|
create :text, page: instance
end
end
trait :with_audio do
after(:create) do |instance, evaluator|
create :audio, page: instance
end
end
end
# text_factory.rb & audio_factory.rb
(...)
瞬态属性有一些重复。不知道怎么干它...