how to define factories with a inheritance user model

痴心易碎 提交于 2019-11-27 22:59:57

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/13343876/how-to-define-factories-with-a-inheritance-user-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!