【发布时间】:2016-04-14 18:38:01
【问题描述】:
我正在尝试测试一个用于创建文章翻译的系统,其中发布表上有一个自联接。我创建了一个工厂,它将创建多个翻译并将它们与“父”文章相关联。
将 Rails 5 与 factory_girl 4.7.0、rspec 和 Database_cleaner 一起使用
所有操作都按预期工作,但创建测试是个问题
以下是相关的模型验证和方法:
# models/publication.rb
has_many :translations, class_name: "Publication", foreign_key: "translation_id", dependent: :nullify
belongs_to :translation, class_name: "Publication", optional: true
validates :language, uniqueness: { scope: :translation_id }, if: :is_translation?
def is_translation?
!translation.nil?
end
工厂(无关代码省略):
# spec/factories/publication.rb
factory :publication, aliases: [:published_pub] do
title 'Default Title'
language 'EN'
published
after(:build) do |object|
create(:version, publication: object)
end
#-- This is where I suspect the problem stems from
trait :with_translations do
association :user, factory: :random_user
after(:build) do |object|
create_list(:translation, 3, {user: object.user, translation:object})
end
end
end
factory :translation, class: Publication do
sequence(:title) { |n| ['French Article', 'Spanish Article', 'German Article', 'Chinese Article'][n]}
sequence(:language) { |n| ['FR', 'ES', 'DE', 'CN'][n]}
user
end
还有一个基本测试:
# spec/models/publication_spec.rb
before(:each) do
@translation_parent = create(:publication, :with_translations)
@pub_without_trans = create(:publication, :with_random_user)
end
scenario 'is_translation?' do
# No actual test code needed, this passes regardless
end
scenario 'has_translations?' do
# No actual test code needed, this (and subsequent tests) fail regardless
end
最后报错:
Failure/Error: create_list(:translation, 3, {user: object.user, translation:object})
ActiveRecord::RecordInvalid:
Validation failed: Language has already been taken
第一个测试通过(并且正确创建了带有翻译的发布对象),但任何后续测试都失败了。问题是我有一个范围为 translation_id 的唯一性验证,而且 factorygirl 似乎正试图将生成的翻译添加到已经存在的出版物中,而不是创建一个全新的出版物。
感谢任何帮助!
【问题讨论】:
标签: ruby-on-rails testing rspec factory-bot ruby-on-rails-5