1

Factory Girl を使用して has_many スルー リレーションシップを設定するのに苦労しています。私は 2 つのモデル コースとカテゴリを持っています。コースは多くのカテゴリを持つことができます。私は 2 つのファクトリー コースとカテゴリを持っています。

私はこの3つのモデルを持っています

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

テストの実行時に発生するエラーは次のとおりです。

パートナーにはコースの有効なファクトリがあります 失敗/エラー: expect(FactoryGirl.create(:course)).to be_valid ActiveRecord::RecordInvalid: 検証に失敗しました: 名前は既に使用されています

私がやりたいのは、1 つ以上のカテゴリを持つコースを作成することです。ここで何が間違っているのかわかりませんが、コース ファクトリを有効にする必要があります。私のカテゴリ ファクトリが有効であることはわかっています。

カテゴリを 2 回作成しようとしているようです。そのため、名前が既に存在するというエラーが発生しています。

4

1 に答える 1