How to define factory girl in rails for model that isn't in root of the models folder?

好久不见. 提交于 2021-02-07 20:23:43

问题


I would like to create a factory girl for a model in my server which is inside a folder in the models folder.

My tree view looks like:

├── app 
|   ├── models
│   │   ├── xxx 
│   │   |   ├── user.rb
├── spec 
│   ├── factories
│   │   ├── xxx
│   │   |   ├── user.rb

My factory girl looks like:

FactoryGirl.define do
  factory :user do
    username { 'aaa' }
  end
end

When I try to build user I get the error:

undefined method `new' for User:Module


回答1:


Is your model defined under a namespace? For example, if your app/models/xxx/user.rb defines a class:

class XXX::User
  #...
end

Then in your factory you can do:

FactoryGirl.define do
  factory :user, class: XXX::User do
    username { 'aaa' }
  end
end


来源:https://stackoverflow.com/questions/28265122/how-to-define-factory-girl-in-rails-for-model-that-isnt-in-root-of-the-models-f

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