FactoryGirl has_many:通过在Rails 3.2.11中打破的关系

时间:2013-01-15 04:42:52

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

一切都按预期工作,直到我升级到Rails 3.2.11。

这就是我的模型的设置方式:

class Student < ActiveRecord::Base
    has_many :institutes
    has_many :teachers, :through => :institutes
end

class Teacher < ActiveRecord::Base
    has_many :institutes
    has_many :students, :through => :institutes
end

class Institute < ActiveRecord::Base
    belongs_to :teachers
    belongs_to :students
    validates :teacher_id, :presence => true
    validates :student_id, :uniqueness => {:scope  => :teacher_id}, :presence => true
end

我的factories.rb文件如下所示:

factory :student do
    first_name "abc"
    last_name "xyz"
    teachers {|t| [t.association(:teacher)] }
end

factory :teacher do
    first_name "ABC"
    last_name "XYZ"
end

factory :institute do
    association :student
    association :teacher
end

问题:

当我这样做时:

FactoryGirl.create(:student)

它给了我以下错误:

ActiveRecord::RecordInvalid: Validation failed: Institutes is invalid

似乎,它会创建:teacher,然后是:institute,最后是:student。因此,它在创建student_id时没有:institute,使其无效。

奇怪的是,相同的模型和factory_girl设置在Rails 3.2.8中运行良好。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

这样的事情

factory :student do |student|  
  ...
  student.after_create do |student|  
    student.teachers << :teacher  
  end  
end  

答案 1 :(得分:2)

尝试:

factory :student do
    first_name "abc"
    last_name "xyz"
end

factory :teacher do
    first_name "ABC"
    last_name "XYZ"
end

factory :institute do
    student
    teacher
end

然后:

@institute = FactoryGirl.create(:institute)
@student = @institute.student

这适用于验证。