我有用户和教师模型。教师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
用户。我该如何解决这个问题?
答案 0 :(得分:6)
您应该定义关联:
Factory.define :teacher do |teacher|
...
teacher.user
end
Factory Girl有wonderful tutorial,我建议你去看看。
P.S。为什么要将这些奇怪的前缀(user_
,teacher_
)添加到模型属性中?它看起来很丑陋,所以你肯定做错了。