2014-11-06 148 views
-1

我有一个我试图测试的rails应用程序。在这个应用程序中,我有一个问题模型,它有很多答案。FactoryGirl没有创建关联

class Question < ActiveRecord::Base 
    has_many :answers, dependent: :destroy 
    accepts_nested_attributes_for :answers, reject_if: lambda { |a| a[:text].blank? }, allow_destroy: true 
    ... 
end 

class Answer < ActiveRecord::Base 
    belongs_to :question 
    ... 
end 

下面来看看我的factories.rb文件,在其中我试图产生许多答案的问题。 (注:我跟着的例子在这里列出https://www.google.com/search?sourceid=chrome-psyapi2&ion=1&espv=2&ie=UTF-8&q=factorygirl%20associations准确,除非我忽视的是,我没有看到的东西。)

factory :question do 
    sequence(:text) { |n| "What is #{n} + #{n}?" } 

    factory :question_with_answers do 
     transient do 
      answers_count 5 
     end 

     after(:create) do |question, evaluator| 
      create_list(:answer, evaluator.answers_count, question: question) 
     end 
    end 
end 

factory :answer do 
    sequence(:text) { |n| "Sample Answer #{n}" } 

    question 
end 

这里是看看规范:

require 'spec_helper' 

describe Question do 
    let!(:question) { FactoryGirl.create :question_with_answers } 

    it "should have 5 anwers" do 
    expect(question.answers.length).to eq 5 
    end 
end 

当我运行这个基本的规范,我得到以下失败/错误:

1) Question should have 5 anwers 
Failure/Error: expect(question.answers.length).to eq 5 

    expected: 5 
     got: 0 

    (compared using ==) 
# ./spec/models/question_spec.rb:17:in `block (2 levels) in <top (required)>' 

我不知道为什么它没有关联的问题的答案。我可以俯视鼻子下面的东西吗?提前致谢。

其他可能有用的信息 - 我使用: factorygirl 4.5.0 轨4.1.5 rspec的3.1.0

+0

尝试使用ID'create_list(:answer,evaluateator.answers_count,question_id:question.id)',如果没有,则尝试将问题直接分配给每个答案。像'answer.question = question; answer.save!' – 2014-11-07 08:13:50

+0

不幸的是,sub_in question_id也不起作用。我已经修改了规范手动分配问题的答案,所以我让它工作 - 它似乎有一个更好的方法来做到这一点。感谢您的回复。 – 2014-11-07 19:43:51

回答

1

想通弄明白了!我所要做的就是实际分配嵌套属性的create_list方法在工厂像这样:

factory :question do 
    sequence(:text) { |n| "What is #{n} + #{n}?" } 

    after(:create) do |question| 
     question.answers = create_list(:answer, 5, question: question) 
    end 

    assessment 
end 

我也不再制造工厂中的工厂(如在我消除了:question_with_answers厂)和而是在分配属性后调用after(:create)方法。希望这可以帮助其他有困难的人。

相关问题