HABTM协会与FactoryGirl

时间:2017-01-22 05:00:39

标签: ruby-on-rails rspec has-and-belongs-to-many

已查看并尝试了大多数示例,但仍然无法创建有效的 HABTM 。无论CaseTrackCaseTrackValue工厂是如何构建的,我都无法在CaseTrack中找到CaseTrackValue[]。不应该在CaseTrack中正确创建CaseTrack提供CaseTrackValue参数 顺便说一句:HABTM的唯一工作协会似乎是

CaseTrack中的

case_track_values { |a| [a.association(:case_track_value)] }

class CaseTrack
 has_and_belongs_to_many CaseTrackValue
end

class CaseTrackValue
 has_and_belongs_to_many CaseTrack
end

Rspec
 it 'may exercise the create action' do
  post '<route>', params: {case_track: attributes_for(:case_track)}
 end
end

class CaseTrackController < ApplicationController
 private:
  def case_track_params
   params.require(:case_track).permit(:name, :active,   {case_track_values:[]})
  end
end

1 个答案:

答案 0 :(得分:0)

看看在我的一个项目中工作的HABTM工厂。我把整个设置放在一个常见的例子中,你可以更深入地了解它,其他stackoverflowers可以轻松地将这个例子用于他们的用例。

所以我们有书籍和类别。可能存在属于许多类别的书籍,并且可能存在包含许多书籍的类别。

<强>模型/ book.rb

class Book < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

<强>模型/ category.rb

class Category < ActiveRecord::Base
  has_and_belongs_to_many :books
end

<强>工厂/ books.rb

FactoryGirl.define do
  factory :book do

    # factory to create one book with 1-3 categories book belongs to
    factory :book_with_categories do
      transient do
        ary { array_of(Book) }
      end
      after(:create) do |book, ev|
        create_list(:category, rand(1..3), books: ev.ary.push(book).uniq)
      end
    end

    #factory to create a book and one category book belongs to
    factory :book_of_category do
      after(:create) do |book, ev|
        create(:category, books: [book])
      end
    end
  end
end

<强>工厂/ categories.rb

FactoryGirl.define do
  factory :category do

    #factory to create category with 3-10 books belong to it
    factory :category_with_books do
      transient do
        ary { array_of(Category) }
        num { rand(3..10) }
      end
      after(:create) do |cat, ev|
        create_list(:book, ev.num, 
          categories: ev.ary.push(cat).uniq)
      end
    end
  end
end

我的辅助方法,您必须将其放在spec/support中的某个位置,然后将其包含在您需要的位置:

 # method returns 0-3 random objects of some Class (obj)
  # for example 0-3 categories for you could add them as association 
  # to certain book
  def array_of(obj)
    ary = []
    if obj.count > 0
      Random.rand(0..3).times do
        item = obj.all.sample
        ary.push(item) unless ary.include?(item) 
      end
    end
    ary 
  end