我一直在努力使用 Factory Girl 通过关系建立 has_many。 我有两个模型类(class)和类别,一个类(class)可以有很多类别,我有两个工厂类(class)和类别。
我有这三个模型
class Course < ActiveRecord::Base
extend FriendlyId
friendly_id :title, use: [:slugged, :history]
has_many :categorisations
has_many :categories, :through=> :categorisations
belongs_to :partner
belongs_to :user
# validates_uniqueness_of :title
validates :title, presence: true
# validates :start_date, presence: true
# validates :duration, presence:true
# validates :state, presence:true
validates :categories, length: { minimum: 1 , message:"please select"}
validates :partner_id, presence: true, allow_nil: false
end
end
class Category < ActiveRecord::Base
has_many :categorisations
has_many :courses, :through=> :categorisations
belongs_to :user
#validation
validates :name, presence: true , uniqueness: { scope: :name }
end
class Categorisation < ActiveRecord::Base
belongs_to :category
belongs_to :course
end
工厂
FactoryGirl.define do
factory :course do |f|
f.title "Introduction to Accounting short course"
f.start_date "2014-02-27 00:00:00"
f.duration "10 WEEKS ONLINE"
partner
categorisation
end
# join table factory - :category
factory :categorisation do |categorisation|
categorisation.association :course
categorisation.association :category
end
end
单个文件中的类别工厂
FactoryGirl.define do
factory :category do |f|
f.name "Marketing"
end
end
我在测试运行时得到的错误是:
合作伙伴有一个有效的类(class)工厂 失败/错误:expect(FactoryGirl.create(:course)).to be_valid ActiveRecord::记录无效: 验证失败:名称已被占用
我想做的是创建一个包含一个或多个类别的类(class),我不确定我在这里做错了什么,但我需要类(class)工厂有效。我知道我的类别工厂是有效的。
它似乎尝试创建一个类别两次,这就是为什么它会出现名称已存在的错误。
最佳答案
您正在创建类(class)两次,一次在顶部,然后在创建分类时再次创建。因为您没有链接到以前创建的类(class),所以 FactoryGirl 会为您创建一个新类(class)。如果您在连接行之前打断,您将看到关联代码中已经存在的内容。
您需要在连接内的行中添加类(class)的细节
categorisation.association :course
例如
categorisation.association (:course, title: "Introduction to Accounting short course")
(抱歉,语法可能略有出入,但你明白了)
关于ruby-on-rails - 运行测试时 has_many 通过 Factory Girl 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293551/