我有模特
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 :(得分: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