ruby-on-rails – FactoryGirl has_many与验证关联

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – FactoryGirl has_many与验证关联前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个标准的has_many关系(预订有很多订单),验证预订不会得到保存,没有至少一个订单.我试图用我的FactoryGirl工厂复制这个,但验证正在阻止我这样做.
class Booking < ActiveRecord::Base
  has_many :orders
  validates :orders,presence: true
end

class Order < ActiveRecord::Base
  belongs_to :booking
end

这是FactoryGirl的GitHub维基页面上的每个型号的FactoyGirl工厂规格.

FactoryGirl.define do                                                    

  factory :booking do                                                                                                                   
    factory :booking_with_orders do

      ignore do                                                                                                                         
        orders_count 1                                                                                                                  
      end                                                                                                                               

      before(:create) do |booking,evaluator|                                                                                           
        FactoryGirl.create_list(:order,evaluator.orders_count,booking: booking)                                                       
      end                                                                                                                               
    end                                                                                                                                 
  end 

  factory :order do
    booking
  end

end

当我尝试从我的规格运行FactoryGirl.create(:booking_with_orders)时,我得到:

Failure/Error: @booking = FactoryGirl.create(:booking_with_orders)
ActiveRecord::RecordInvalid:
  Validation Failed: Orders can't be blank

似乎验证的检查甚至在之前(.创建)[…]运行,这将理论上创建订单的订单.

This post建议不要向工厂添加has_many关系,但是如果有一个很好的方法,我想解决这个问题.

提前致谢.

解决方法

笏?不可能?一点也不.

只需将您的代码更改为如下所示:

after :build do |booking,evaluator|
  booking.orders << FactoryGirl.build_list(:order,booking: nil)
end
原文链接:https://www.f2er.com/ruby/273992.html

猜你在找的Ruby相关文章