我有一个我试图测试的rails应用程序。在这个应用程序中,我有一个问题模型,其中有许多答案。
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 :(得分: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)方法。希望这可以帮助那些遇到麻烦的人。