【问题标题】:FactoryGirl set attribute with associationFactoryGirl 设置属性与关联
【发布时间】:2013-03-09 18:39:54
【问题描述】:

我有一个附加到CourseNote 对象,我想在FactoryGirl 中将@note.number 随机设置为rand(@note.course.sections)。我试过了:

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

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

【问题讨论】:

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


    【解决方案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, ...>
    

    【讨论】:

    • 谢谢,我也应该在控制台中测试它。该错误实际上是由FactoryGirl.attributes_for(:note) 发出的,因为我没有传入course:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多