簡體   English   中英

創建一個使用當前種子記錄的FactoryGirl定義

[英]Creating a FactoryGirl definition that uses a currently seeded record

我遇到了與FactoryGirl的GitHub頁面( #623 )中提出的問題相同的問題,即通過種子數據觸發了唯一性驗證。

我的工廠原本是這樣的:

factory :country, class: MyApp::Models::Country do
  code { MyApp::Models::Country.first.code }
  name { MyApp::Models::Country.first.name }
end

不理想,打碎了短絨,所以我使用#623中的建議進行了重構:

factory :country, class: MyApp::Models::Country do
  intitalize_with { MyApp::Models::Country.find_or_create_by(code: 'GB') }
end

但是我現在在棉絨上得到以下錯誤堆棧:

/Users/philostler/.rvm/gems/ruby-2.1.2/gems/activemodel-4.1.4/lib/active_model/attribute_methods.rb:435:in `method_missing': undefined method `intitalize_with=' for #<MyApp::Models::Country id: nil, code: nil, name: nil> (NoMethodError)
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/activerecord-4.1.4/lib/active_record/attribute_methods.rb:208:in `method_missing'
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:16:in `block (2 levels) in object'
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:15:in `each'
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:15:in `block in object'
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:14:in `tap'
    from /Users/philostler/.rvm/gems/ruby-2.1.2/gems/factory_girl-4.4.0/lib/factory_girl/attribute_assigner.rb:14:in `object'

現在,它試圖在一個空白模型對象上調用intitalize_with =,該對象當然會崩潰。

我只是希望工廠使用已經存在的記錄,同時仍通過皮棉。

我是用錯誤的方式處理還是這里有錯誤(可能是因為我使用的是名稱空間)?

當您使用FactoryGirl並使用常量聲明class ,經常會遇到非相關消息的奇怪錯誤,就像您所做的那樣。 使用字符串解決了我這方面的問題,這當然與自動加載有關。

我不知道這是否是您的解決方案,但是您可以嘗試(對您所有的工廠都可以這樣做)

# Instead of
factory :country, class: MyApp::Models::Country do
  code { MyApp::Models::Country.first.code }
  ...
end

# Do
factory :country, class: 'MyApp::Models::Country' do
  code { MyApp::Models::Country.first.code }
  ...
end

暫無
暫無

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

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