2017-03-31 99 views
1

我遇到的问题特定于与belongs_to和has_many的关系,其中has_many关系至少需要关联一个关联。此要求导致我的工厂无法通过我的模型级别验证,也无法创建。Factory_girl与belongs_to/has_many关联至少有1个关联

我的集团模式

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文档没有提到这个特定的用例。提前致谢。

回答

2

如何像

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

主要的想法是保存之前建立所需的对象。如果您需要更多,您也可以尝试build_list

+0

啊!这工作!哇,我厌倦了这一主题的一些变化,但我的语法错了。很棒,谢谢! – sammms