Valikos Ost
Valikos Ost

Reputation: 355

factory girl multiple nested attributes

I have models

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

I need to create a factory review with 4 nested ratings, it`s for testing review validation, but I dont have any idea how do this This is my factories:

  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

In controller I am writing for init review with nested attrs:

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

and for creating new review with ratings:

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

and all working is good, but I need to test it

Please help me.

Upvotes: 3

Views: 792

Answers (1)

Shevaun
Shevaun

Reputation: 1228

You can add a trait to the review factory and then create reviews with ratings like this: FactoryGirl.create(:review, :with_ratings)

Review factory with trait:

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

Upvotes: 1

Related Questions