how to define factories with a inheritance user model
Asked Answered
J

2

35

I got following problem: In my application i use inheritance to define my user model:

class User
 include Mongoid::Document

 field :name...
 field :bla...
end


class CustomUser < User
 field :customuserfield...
end

How can i write factories to map this Class hirachie in my specs. And keep up writing with don´t repeat yourself.

FactoryGirl.define do 
  factory :user do
    name  "name"
    bla "bla"

    factory :custom_user do
      customfield "customfield"
    end
  end
end

This doesn´t work for me because the class is also "User". With "User" i got a invalid error because the customfields are not defiend here. Is there a good practice, way or method to relize something like that.

Jenelljenelle answered 12/11, 2012 at 12:40 Comment(0)
A
68

You can try this:

factory :user do
  name  "name"
  bla "bla"
end

factory :custom_user, class: CustomUser, parent: :user do
  customfield "customfield"
end

For more info: Inheritance.

Aport answered 12/11, 2012 at 13:22 Comment(2)
yea it worked with parent... but i need to add class: CustomUser--> (factory :custom_user, class:CustomUser, parent: :user )Jenelljenelle
This is exactly the answer I was looking for to my problem. Wish I could upvote this multiple times.Vanadium
L
16

Just add the class: CustomUser to :custom_user factory. That works for me. When you nested in :user it means parent is User, but it is simpler.

FactoryGirl.define do 
  factory :user do
    name  "name"
    bla "bla"

    factory :custom_user, class: CustomUser do
      customfield "customfield"
    end
  end
end
Lynnet answered 23/5, 2014 at 12:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.