Factory Girl has_many通过validation死锁

我有一个Listing模型,其中has_many :categories, through: :categories_listingshas_many :categories_listings 。 我正在用Factory Girl工厂测试它,看起来像这样:

 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 

在我向模型添加以下validation之前,一切正常:

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

现在每当我经营工厂时,我得到:

ActiveRecord::RecordInvalid: You have to add at least one category

我也尝试过像before :create一样的Factory Girl回调before :create但问题是我无法添加关联,因为我还不知道回调中的列表ID。 但我无法保存列表,因为validation是在关联之前运行的。

我怎样才能解决这个问题并让它发挥作用?

使它工作。

在我的工厂中,我删除了类别行并添加了一个before(:create)回调来建立关系。 强调构建,因为它不适用于创建(我在发布问题之前尝试过)。 另外,我还提到了可以解决僵局的问题。 所以现在,工作工厂看起来像这样:

 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 

从这个答案得到了我的灵感。