Factory Girl多层嵌套属性

3
我有模型。
class Rating < ActiveRecord::Base
  attr_accessible :type_id, :value
  belongs_to :review

class Review < ActiveRecord::Base
  attr_accessible :name, :description, :user_id, :relationship_type_id, :ratings_attributes    
  belongs_to :facility
  has_many :ratings
  accepts_nested_attributes_for :ratings, limit: Rating::RATE.count

我需要创建一个工厂审查,其中包含4个嵌套的评分,这是为了测试审查验证,但我不知道如何做。这是我的工厂:
  factory :review do
    facility
    sequence(:name) { |n| "Name of review #{n}" }
    sequence(:description) { |n| "asdasdasdasdasdasd #{n}" }
    user_id 1
    relationship_type_id 1
  end
  factory :rating do
    type_id 2
    value 3
    review  
    factory :requred_rating do
      type_id 1
    end
  end

我正在为初始化评估编写控制器,其中包含嵌套的属性:

  @review = Review.new
  Rating::RATE.each do |rate|
    @review.ratings.build(type_id: rate[1])
  end

创建包含评级的新评论:

  @review = @facility.reviews.build(params[:review])
  if @review.save

一切工作正常,但我需要测试它。

请帮助我。


我找到了解决我的问题的方法。 - Valikos Ost
1个回答

1
你可以为评论工厂添加一个特征,然后像这样创建带有评分的评论:FactoryGirl.create(:review, :with_ratings) 具有特征的评论工厂:
factory :review do
  facility
  sequence(:name) { |n| "Name of review #{n}" }
  sequence(:description) { |n| "asdasdasdasdasdasd #{n}" }
  user_id 1
  relationship_type_id 1

  trait :with_ratings do
    after(:create) do |review|
       Rating::RATE.each do |rate|
         FactoryGirl.create(:rating, review: review, type_id: rate[1])
       end 
    end
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接