簡體   English   中英

FactoryGirl,其belongs_to / has_many關聯至少具有1個關聯

[英]FactoryGirl with belongs_to / has_many association with minimum of 1 association

我遇到的問題是特定於與一個ares_many關系具有至少一個關聯的要求的,與一個belongs_to和has_many的關系。 此要求導致我的工廠無法進行模型級別驗證,因此無法創建。

我的群組模型

Group < ActiveRecord::Base
  has_many :organizations, dependent: nullify
  # commenting out the following line will make the tests pass
  validates :organizations, presence: true
  ...
end

組織模式

Organization < ActiveRecord::Base
  belongs_to :group
  ...
end

組織工廠

FactoryGirl.define do
  factory :organization
    name "test organization"
  end
end

最后是問題孩子:集團工廠

FactoryGirl.define do
  factory :group do
    name "test group"
    after(:create) do |group|
      create(:organization, group: group)
    end
  end
end

在測試中,我聲明了工廠實例:

describe "something happens with a Group" do
  let(:group) { FactoryGirl.create :group }

  it "should work" do
    ...
  end
end

我的測試返回的錯誤多種多樣,但通常都表明FactoryGirl無法創建Group工廠的實例。 例如

# when a test relies on creating an instance of 'Group'
ActiveRecord::RecordInvalid:
    Validation failed: Organizations can't be blank 

我使用(回調)創建我的工廠工廠的方法來自於Thoughtbot的帖子https://robots.thoughtbot.com/aint-no-calla-back-girl

有很多類似的文章,但是我發現的所有文章以及Thoughtbot文檔都沒有提到這個特定的用例。 提前致謝。

怎么樣

FactoryGirl.define do
  factory :group do
    name 'test group'
    organizations { [association(:organization)] }
  end
end

主要思想是在保存所需對象之前先對其進行構建。 如果需要更多內容,也可以嘗試使用build_list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM