5

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?

phs
  • 10,687
  • 4
  • 58
  • 84
vmcloud
  • 650
  • 4
  • 13

1 Answers1

6

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
joelparkerhenderson
  • 34,808
  • 19
  • 98
  • 119
  • 1
    This will work for this particular case, but will break if that value were `nil` or `false`. It is better to use `defined?` or its kins. – sawa Mar 17 '15 at 08:45