【问题标题】:factory girl multiple nested attributes工厂女孩多重嵌套属性
【发布时间】:2012-11-28 15:14:02
【问题描述】:

我有模型

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

一切正常,但我需要测试一下

请帮帮我。

【问题讨论】:

  • 我找到了解决问题的方法

标签: ruby-on-rails rspec factory-bot nested-attributes


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多