如何使用继承用户模型定义工厂

35

我遇到了以下问题: 在我的应用程序中,我使用继承来定义我的用户模型:

class User
 include Mongoid::Document

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


class CustomUser < User
 field :customuserfield...
end

我该如何编写工厂函数以在我的规范中映射此类层次结构,并保持DRY原则。

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

    factory :custom_user do
      customfield "customfield"
    end
  end
end

这对我不起作用,因为类名也是"User"。在 "User" 上,我得到了一个无效错误,因为这里没有定义自定义字段。有没有一种好的实现方式或方法来实现这样的事情。

2个回答

67

你可以尝试这样做:

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

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

更多信息请参考:继承


1
没错,它与父类一起工作了...但我需要添加类:CustomUser-->(factory: custom_user,class: CustomUser,parent: user) - bulleric
这正是我寻找解决问题的答案。真希望我能多次点赞。 - Alvin S. Lee

16

只需将类别名CustomUser添加到:custom_user 工厂中即可。这对我很有效。当您将其嵌套在:user 中时,它意味着父级是用户(User),但这样更简单。

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接