From: ded Date: 2005-09-04T02:36:26+09:00 Subject: 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 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.