FactoryGirl设置属性与关联

时间:2013-03-09 18:39:54

标签: ruby-on-rails rspec tdd factory-bot

我有一个Note对象附加到Course,我想在FactoryGirl中随机设置@note.numberrand(@note.course.sections)。我试过了:

  factory :note do
    association :course
    number { ranb(course.sections) }
    content { Faker::Lorem.paragraphs(paragraph_count = 1).join(" ") }
  end

它不起作用,并表示课程是零。这样做的正确方法是什么?谢谢!

1 个答案:

答案 0 :(得分:1)

我不理解Course#sectionsNote#number之间的关系,我也只能假设你定义了Course工厂。我测试了以下内容,它运行正常:

FactoryGirl.define do
  factory :course do
    sequence(:sections)
  end

  factory :note do
    course
    number { rand(course.sections) }
  end
end


note = FactoryGirl.create(:note)
# => <Note id: 11, course_id: 12, number: 6, ...>
note.course
# => <Course id: 12, sections: 9, ...>