Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Chefspec反复加载库并发出警告;“已初始化常量”;_Ruby_Chef Infra_Chefspec - Fatal编程技术网

Ruby Chefspec反复加载库并发出警告;“已初始化常量”;

Ruby Chefspec反复加载库并发出警告;“已初始化常量”;,ruby,chef-infra,chefspec,Ruby,Chef Infra,Chefspec,我有一本带图书馆的厨师烹饪书,例如library.rb。它包含一个常量: CONSTANT = 'constant' 当我为这本食谱编写单元测试时,它总是给我一个警告: (Some prefix...)warning: already initialized constant CONSTANT (Some prefix...)warning: previous definition of CONSTANT was here 警告会反复出现,就像示例数(测试用例)减去1一样多。我认为这是因为c

我有一本带图书馆的厨师烹饪书,例如
library.rb
。它包含一个
常量

CONSTANT = 'constant'
当我为这本食谱编写单元测试时,它总是给我一个警告:

(Some prefix...)warning: already initialized constant CONSTANT
(Some prefix...)warning: previous definition of CONSTANT was here

警告会反复出现,就像示例数(测试用例)减去1一样多。我认为这是因为chefspec为每个示例加载一次库。有人能告诉我如何使库只加载一次,或者如何禁用警告消息吗?

短期内,将其更改为:

CONSTANT ||= 'constant'
从长远来看,最好使用
let()
,或者将常量移出测试用例,或者选择任何其他方式替换常量,或者确保测试代码加载库一次,而不是多次

编辑——注释中@sawa的观点很好:如果常数为
nil
false
,则
|124;=
方法不会停止警告,因此您需要更好的解决方案,例如:

CONSTANT = 'constant' unless defined? CONSTANT

常量
是一个常量,不是一个变量。这将适用于此特定情况,但如果该值为
nil
false
,则该值将中断。最好使用
defined?
或其kins。