没有class_name的FactoryBot命名空间模型 [英] FactoryBot namespaced models without class_name

查看:72
本文介绍了没有class_name的FactoryBot命名空间模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样命名的模型:

I have models which are namespaced such as this:

class Vehicle < ActiveRecord::Base; end

class Vehicle::Car < Vehicle; end
class Vehicle::Train < Vehicle; end
class Vehicle::Jet < Vehicle; end

在为这些模型创建工厂时,它们是通过以下方式设置的:

When creating factories for these models, they were set up in the following way:

factory :vehicle_car, class: Vehicle::Car do; end
factory :vehicle_train, class: Vehicle::Train do; end
factory :vehicle_jet, class: Vehicle::Jet do; end

这会产生以下弃用警告:

This produces the following deprecation warning:

建议不要使用:按类查找工厂,并且将在5.0版中将其删除。使用符号代替并设置FactoryBot.allow_class_lookup = false。

DEPRECATION WARNING: Looking up factories by class is deprecated and will be removed in 5.0. Use symbols instead and set FactoryBot.allow_class_lookup = false.

是否存在用于编写符号来命名这些工厂的格式,以便

Is there a format for writing a symbol to name these factories such that I do not need to use the class name to comply with the deprecation warning?

推荐答案

该文档对于如何使用该类名并不是非常有用。 :class 选项的行为或预期的值,但其来源更为有用。从错误消息回溯,我们发现 FactoryBot :: Decorator :: ClassKeyHash#symbolize_keys

The documentation wasn't terribly useful as to how the :class option behaves or what it expects as its value but the source was more helpful. Backtracking from the error message we find FactoryBot::Decorator::ClassKeyHash#symbolize_keys:

def symbolized_key(key)
  if key.respond_to?(:to_sym)
    key.to_sym
  elsif FactoryBot.allow_class_lookup
    ActiveSupport::Deprecation.warn "Looking up factories by class is deprecated and will be removed in 5.0. Use symbols instead and set FactoryBot.allow_class_lookup = false", caller
    key.to_s.underscore.to_sym
  end
end

第一个分支中的 key.to_sym 是我想要一个符号 String 。第二个分支中的 key.to_s.underscore.to_sym 告诉我们期望的格式。

The key.to_sym in the first branch is the usual idiom for "I want a Symbol or String". The key.to_s.underscore.to_sym in the second branch tells us what format is expected.

如果运行 Vehicle :: Car 通过 to_s.underscore ,您将获得'vehicle / car' code>,因此它们应该起作用:

If you run Vehicle::Car through to_s.underscore, you get 'vehicle/car' so these should work:

factory :vehicle_car,   class: 'vehicle/car'   do; end
factory :vehicle_train, class: 'vehicle/train' do; end
factory :vehicle_jet,   class: 'vehicle/jet'   do; end

或者如果您真的想要 Symbol (或者有标点符号):

or if you really want Symbols (or have a thing for punctuation):

factory :vehicle_car,   class: :'vehicle/car'   do; end
factory :vehicle_train, class: :'vehicle/train' do; end
factory :vehicle_jet,   class: :'vehicle/jet'   do; end

这篇关于没有class_name的FactoryBot命名空间模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆