使用瞬态FactoryGirl创建多个唯一条目

时间:2015-12-16 09:07:58

标签: ruby ruby-on-rails-4 factory-bot

我有一个FactoryGirl对象,在我的情况下创建Category(它与图像相关联)

class Image < ActiveRecord::Base
  has_many :image_categories, dependent: :destroy
  has_many :categories, through: :image_categories
  validates :categories, presence: { message: 'Choose At Least 1 Category' }
end

class Category < ActiveRecord::Base
  has_many :image_categories
  has_many :images, through: :image_categories
  validates :name, presence: { message: "Don't forget to add a Category" }
  validates_uniqueness_of :name, message: 'Category name %{value} already exists'
end


FactoryGirl.define do
 factory :category do
  name 'My Category'
 end
end 

FactoryGirl.define do
  factory :image do
    title 'Test Title'
    description 'Test Description'
    transient do
      categories_count 1
   end
   categories { build_list(:category, categories_count) }
 end
end

创建一个类别的图像时,一切都很好,但是如果我尝试保存2个类别,则第二个条目会保存为nil,我想这是因为我对唯一名称的验证。

所以我的问题是如何使用瞬态来创建2个独特类别的列表

希望这是有道理的

由于

1 个答案:

答案 0 :(得分:0)

直接来自Factory Girl文档:http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md#Transient_Attributes

FactoryGirl.define do

  # post factory with a `belongs_to` association for the user
  factory :post do
    title "Through the Looking Glass"
    user
  end

  # user factory without associated posts
  factory :user do
    name "John Doe"

    # user_with_posts will create post data after the user has been created
    factory :user_with_posts do
      # posts_count is declared as a transient attribute and available in
      # attributes on the factory, as well as the callback via the evaluator
      transient do
        posts_count 2
      end

      # the after(:create) yields two values; the user instance itself and the
      # evaluator, which stores all values from the factory, including transient
      # attributes; `create_list`'s second argument is the number of records
      # to create and we make sure the user is associated properly to the post
      after(:create) do |user, evaluator|
        create_list(:post, evaluator.posts_count, user: user)
      end
    end
  end
end