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

所有工作都很好,但我需要测试它

请帮我。

4

1 回答 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
于 2013-07-18T06:04:40.920 回答