already initialized constant in fixtures

Following the dynamic fixture example from most of the rail’s books and tutorials available out there… you would be tempted to add something like this to the top of your fixture. ( this example is particularly relevant to the users fixture for use with the LoginEngine)

[source:ruby]<% SALT = "nacl" %> [/source]and then you would use this constant in your fixture somewhere… like maybe

   salt: <%= SALT %>   salted_password: <%= LoginEngine::AuthenticatedUser.salted_password     (SALT, LoginEngine::AuthenticatedUser.hashed('secret'))%> 

This is good for a single use of this fixture. But if more than one unit tests or functional tests load this fixture, you will start getting a warning “already initialize constant SALT” for all but the first use of the fixture.
Though it is just a warning, I did not find a mention of this in any of the books/tutorials.

Just a small check for an already defined constant will fix this warning.

 <% SALT = "nacl" unless self.class.const_defined?("SALT") %> 

Comments

  1. This is a common idiom from other areas of your application too, like controllers and models:

    SALT = “nacl”.freeze unless const_defined? “SALT”

    Note the freeze. The constantness of an object just prevents replacement of that object with another. Freezing the object ensures its attributes can’t be changed.

Leave a Reply

Your email address will not be published. Required fields are marked *

thirty − = twenty seven