Rails 3 - 工厂女孩宝石 - belongs_to和has_one关系

时间:2012-03-21 17:35:58

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

我有用户教师模型。教师belongs_to用户和用户has_one教师。我还有工厂女孩文件中的代码:

Factory.define :user do |user|
  user.user_login "Another User"
  user.user_role "admin"
  user.password "foobar"
end

Factory.sequence :user_login do |n|
  "person-#{n}"
end

Factory.define :teacher do |teacher|
  teacher.teacher_last_name   'Last'
  teacher.teacher_first_name  'First'
  teacher.teacher_middle_name 'Middle'
  teacher.teacher_birthday    '01.11.1980'
  teacher.teacher_category    'First category'
  teacher.teacher_sex         'm'
end

当我尝试在我的规范中创建教师时:

@teacher = Factory(:teacher)

然后我收到错误:

Failure/Error: @teacher = Factory(:teacher)
     ActiveRecord::RecordInvalid:
       Validation failed: User can't be blank

据我了解,因为我没有告诉Factory我的老师belongs_to用户。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:6)

您应该定义关联:

Factory.define :teacher do |teacher|
  ...
  teacher.user
end

Factory Girl有wonderful tutorial,我建议你去看看。

P.S。为什么要将这些奇怪的前缀(user_teacher_)添加到模型属性中?它看起来很丑陋,所以你肯定做错了。