2015-12-16 6 views
0

У меня есть FactoryGirl объект, который создает в моем случае с Category (он связан с изображением)Создание нескольких уникальных записей с временными FactoryGirl

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 уникальных категорий

Надежда это имеет смысл

Благодаря

ответ

0

Направьте от фабрики девушки Документация: 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 
Смежные вопросы