通过验证僵局工厂女孩的has_many [英] Factory Girl has_many through validation deadlock

查看:86
本文介绍了通过验证僵局工厂女孩的has_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单模式,的has_many:类别,通过:categories_listings 的has_many:categories_listings 。我是一个工厂女孩工厂,看起来像这样测试它:

I have a Listing model which has_many :categories, through: :categories_listings and has_many :categories_listings. I was testing it with a Factory Girl factory which looks like this:

factory :listing do |f|
  f.sequence (:title) { |n| "Listing #{n}" }
  message {Faker::Lorem.paragraph}
  cards {[FactoryGirl.create(:card)]}
  categories {[FactoryGirl.create(:category)]}
  association :delivery_condition
  association :unit_of_measure
  quantity 1
  unit_price 1
end

和,直到我说了以下验证的模型一切正常:

And everything was OK until I added the following validation to the model:

validate :has_categories?

def has_categories?
  if self.categories_listings.blank?
    errors.add :base, "You have to add at least one category"
  end
end

现在,每当我跑了工厂,我得到:

Now whenever I run the factory I get:

的ActiveRecord :: RecordInvalid:您必须添加至少一个类别

我也试图与工厂女孩回调像之前:创建但问题是,我不能添加的关联,因为我还不知道在上市ID回调。但我不能挽救上市,因为验证是该协会之前运行。

I also tried with Factory Girl callbacks like before :create but the problem is that I can't add the association because I don't yet know the listing id in the callback. But I can't save the listing because validations are run before the association.

我怎样才能解决这个问题,并使其发挥作用?

How can I get around this and make it work?

推荐答案

使它工作。

在我厂我删除类别行,并添加了之前(:创建)回调而 BUILDS 的关系。强调建立,因为它不会与创建工作(我想,发布这个问题之前)。再加构建绕过僵局,我提。所以,现在,工作的工厂看起来是这样的:

In my factory I removed the categories line and added a before(:create) callback which BUILDS the relationship. Emphasis on builds as it wouldn't work with create (I tried that before posting the question). Plus build bypasses the deadlock I was mentioning. So now, the working factory looks like this:

factory :listing do |f|
  f.sequence (:title) { |n| "Listing #{n}" }
  message { Faker::Lorem.paragraph }
  cards { [FactoryGirl.create(:card)] }
  association :delivery_condition
  association :unit_of_measure
  quantity 1
  unit_price 1

  before(:create) do |listing|
    category = FactoryGirl.create(:category)
    listing.categories_listings << FactoryGirl.build(:categories_listing, listing: listing, category: category)
  end
end

得到了我的灵感来自这个答案

这篇关于通过验证僵局工厂女孩的has_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆