【问题标题】:How to define Fabricator for namespace class如何为命名空间类定义 Fabricator
【发布时间】:2013-01-30 08:44:56
【问题描述】:

我想为具有类似 'Foo::Bar' 的命名空间的类定义 Fabricator。
告诉我它的工作原理。

这是我的代码。

models/foo.rb

class Foo
  include Mongoid::Document
  embedded_in :foo_container, polymorphic: true

  field :xxx ....
end

models/foo/bar.rb

class Foo::Bar < Foo
  field :yyy ....
  field :zzz ....
end

数据/fabricators/foo_bar_fabricator.rb

Fabricator(:foo_bar, class_name: 'Foo::Bar') do
   yyy 'MyString'
   zzz 'MyString'
end

当我尝试在 parino 控制台上创建 Fabricatior 对象但发生错误时。

> Fabricate(:foo_bar)
> NoMethodError: undefined method `new?' for nil:NilClass
  .... stack messages

当我尝试创建其他 Fabricator 对象不是像“用户”这样的命名空间类时,它成功了。

【问题讨论】:

    标签: ruby mongoid fabrication-gem


    【解决方案1】:

    根据 Fabrication 在 creating objects 上的文档:

    要使用与类不同的名称,您必须指定 from: :symbolized_class_name 作为第二个参数。

    所以以下应该可以工作:

    Fabricator(:foo_bar, from: 'Foo::Bar') do
      yyy 'MyString'
      zzz 'MyString'
    end
    

    【讨论】:

      【解决方案2】:

      这对我有用

      Fabricator(:foo_bar, class_name: :'Foo::Bar') do
          xxx {Faker::Company.name}
          yyy 'Mystring'
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        • 2015-03-17
        • 1970-01-01
        • 2011-01-15
        • 2014-10-18
        • 2019-06-23
        相关资源
        最近更新 更多