Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chefspec loads libraries repeatedly and gives the warning "already initialized constant CONSTANT"

I have a chef cookbook with a library, e.g. library.rb. It contains a CONSTANT:

CONSTANT = 'constant'

When I write unit tests for this cookbook, it always gives me the warning:

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

The warnings come up repeatedly, as many times as the number of examples (test cases) minus one. I think it is because chefspec loads the libraries once for each example. Could someone tell me how to make the libraries load only once, or how to disable the warning message?

like image 969
vmcloud Avatar asked Mar 17 '15 07:03

vmcloud


1 Answers

Short term, change it to:

CONSTANT ||= 'constant'

Long term, it's better to use a let(), or to move the constant out of the test case, or to choose any other way of replacing the constant, or to ensure the testing code loads the library once, not many times.

Edit -- Good point by @sawa in the comments: if your constant is nil or false, then the ||= approach doesn't stop the warnings, so you'll want a better solution such as:

CONSTANT = 'constant' unless defined? CONSTANT
like image 83
joelparkerhenderson Avatar answered Oct 07 '22 00:10

joelparkerhenderson