ExiRe
ExiRe

Reputation: 4767

Rails 3 - Factory girl gem - belongs_to and has_one relation

I have User and Teacher models. Teacher belongs_to User and User has_one Teacher. Also i have the code in factory girl file:

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

When i try to create a teacher in my spec:

@teacher = Factory(:teacher)

Then I recieve the error:

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

As i understand that happens because i don't tell Factory that my teacher belongs_to user. How can i fix that?

Upvotes: 1

Views: 3582

Answers (1)

Nash Bridges
Nash Bridges

Reputation: 2378

You should define association:

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

Factory Girl has wonderful tutorial, I recommend you to look at it.

P.S. Why would you want to add those strange prefixes (user_, teacher_) to model attributes? It looks very ugly, so you definitely do something wrong.

Upvotes: 6

Related Questions