Rails 4和FactoryGirl特性创建

时间:2013-06-03 09:53:45

标签: ruby-on-rails factory-bot ruby-on-rails-4

我们将rails3应用程序迁移到Rails4。在FactoryGirl中我们使用这个特性:

trait :with_student do
    after_create do |resource|
      resource.students << FactoryGirl.create(:student)
    end
  end

在模型rspec中:

  let(:course_with_student) { create(:course, :with_student) }

我提出了course_with_student并给了我课程对象。但是当提高course_with_student.students输出时:  #<ActiveRecord::Associations::CollectionProxy []>。在特征定义资源中引发异常。学生和学生对象存在,但在rspec模型规范中没有。

1 个答案:

答案 0 :(得分:0)

我通常使用特征的方式是after_build块。试试这样的事情:

trait :with_student do
  after_build do |course|
    course.students = FactoryGirl.create_list(:student, 1)
  end
end

对我来说,解决了我遇到的一些类似问题。