【问题标题】:Creating multiple unique entries with transient FactoryGirl使用瞬态 FactoryGirl 创建多个唯一条目
【发布时间】:2015-12-16 09:07:57
【问题描述】:

我有一个 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

当创建具有 1 个类别的图像时,一切都很好,但如果我尝试使用 2 个类别保存第二个条目将保存为 nil,我想这是因为我验证了唯一名称。

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

希望这是有道理的

谢谢

【问题讨论】:

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


    【解决方案1】:

    直接来自 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多