ruby-on-rails - 运行测试时 has_many 通过 Factory Girl 错误

标签 ruby-on-rails ruby testing factory-bot factories

我一直在努力使用 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/

相关文章:

ruby-on-rails - 下载大文件(~40MB)并使用回形针另存为附件

ruby-on-rails - 无法理解 rails activerecord typecast 的原因

unit-testing - 可以获取任何类型的结构函数

typescript - 在 VS Code 下进行 mocha 调试以使用 mocha 的 --file 选项启动每个测试

ruby-on-rails - rails : Custom nested controller actions

ruby-on-rails - PG gem 不会安装在 Rails 应用程序中:Gem::Ext::BuildError: ERROR: Failed to build gem native extension

ruby-on-rails - 在索引 View 问题中呈现 'belongs_to"- Ruby on Rails

ruby-on-rails - 释放 Rails 中的连接

testing - 如何在 jmeter 的 HTTP 请求(路径)中给出通用值/id?

ruby-on-rails - Rails 使用 API