2012-11-28 101 views
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 

在控制器我寫嵌套ATTRS INIT回顧:

@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 

和所有的工作是好的,但我需要測試它

請幫助我。

+0

我發現我的問題 –

+3

的解決方案,你應該分享。 .. – hellion

回答

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