Newbie Q: Self-Testing Ruby Files (Double Assignment to Constants)

I like to make class files self-testing and can do so with the
following arrangement:

==================== Junk.rb ==========================
Class Junk
  CONST = 'a value'
  def initialize
  end
end

# Unit tests
if __FILE__ == $0
    require 'test/TestJunk.rb'
end

===================== test/TestJunk.rb ==================
require 'test/unit'
require 'Junk' unless defined?(CONST)

class TestJunk < Test::Unit::TestCase
    def test_sometest
        assert(<<some assertion>>, "Some message")
    end
end

···

==========================================================

The thought is that I can run Junk.rb or TestJunk.rb as a top-level
script and have the unit tests run either way.

This works, EXCEPT if I run Junk.rb it complains that I have already
assigned to CONST, so it is apparently loading Junk.rb twice.

I tried to avoid these with the if defined?(CONST) construct, but ot
does not help.

Questions:

1. I thought the 'require' method would load the file only if it was
not loaded already. If so, how could two requires result in two
executions of the CONST = 'some value' line? There's something I'm not
getting here.

2. Why doesn't the "if defined?(CONST)" thingy help? I would think it
is unnecessary given my assumption in 1. I'm definitely confused.

Ruby-Nuby in need of guidance.

Thanks.

- require 'Junk' unless defined?(CONST)
+ require 'Junk' unless defined?(Junk::Const)

-austin

···

On 9/3/05, ded <ded-google@ddoherty.net> wrote:

===================== test/TestJunk.rb ==================
require 'test/unit'

--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca

Hi --

I like to make class files self-testing and can do so with the
following arrangement:

==================== Junk.rb ==========================
Class Junk

class, not Class :slight_smile:

CONST = 'a value'
def initialize
end
end

# Unit tests
if __FILE__ == $0
   require 'test/TestJunk.rb'
end

===================== test/TestJunk.rb ==================
require 'test/unit'
require 'Junk' unless defined?(CONST)

You've defined CONST inside Junk, but you're testing for it at the top
level. Try this:

   require 'Junk' unless defined?(Junk::CONST)

David

···

On Sun, 4 Sep 2005, ded wrote:

--
David A. Black
dblack@wobblini.net

Thanks, both.

But shouldn't 'require' not need that sort of test? Should it not know
that the module was already loaded?

It shouldn't. Using ruby 1.8.2 (2004-12-25) [i386-mswin32], I didn't
experience any warnings to the effect you suggested.

-austin

···

On 9/4/05, ded <ded-google@ddoherty.net> wrote:

Thanks, both.

But shouldn't 'require' not need that sort of test? Should it not know
that the module was already loaded?

--
Austin Ziegler * halostatue@gmail.com
               * Alternate: austin@halostatue.ca