我的Rails应用程序中有一个服务对象,如果没有正确配置,则会引发ConfigurationError
:
module Import
class ImportedObject
...
def initialize(*args)
raise ConfigurationError unless Import.configured?
super
end
...
end
end
在开发过程中一切运行良好。然而,运行rspec会立即失败.../app/services/import/imported_object.rb:16:in 'initialize': Import should be configured with 'Import.configure_for company, origin' (Import::ConfigurationError)
,即使没有规范触及任何Import类(尚未;))。
这是由Rails在除开发之外的所有环境中的所有类的自动加载(并且显然正在初始化?)引起的吗?
如何正确加载此类,并且仍能在配置丢失时引发异常?
答案 0 :(得分:0)
在运行任何测试之前,rspec准备环境 - 这意味着它执行application.rb,environment.rb和所有初始化程序。你在那里初始化你的进口吗?
答案 1 :(得分:0)
所以我想通了,似乎这个问题不是由Rails或rspec引起的。
我正在使用Virtus来定义ImportObject
及其子类中的属性。
我还在扩展了ImportObject的DSL模块中定义了一个composed_of
方法,它在几个子类中使用:
# DSL for composition
def composed_of(klass, attribute_name, options = {})
...
# Set an attribute that contains the proxied class and delegate methods defined in constant
attribute attribute_name, klass, default: klass.new
...
end
klass.new
是导致异常的原因,将其置于proc中解决了这个问题。我想当rspec初始化时会评估composed_of
。