0

There is a class in a ruby file test.rb

#test.rb
class AAA<TestCase
  def setUp()
     puts "setup"
  end
  def run()
     puts "run"
  end
  def tearDown()

  end
end

In another file test2.rb, i want to get the instance of AAA by file name "test.rb". In python, i can do this by below:

casename = __import__ ("test")
for testcase in [getattr(casename, x) for x in dir(casename)]:
    if type(testcase) is type and issubclass(testcase, TestCase):
             #do something with testcase()

How can i implement the same function in ruby now. Thanks

KGo
  • 18,536
  • 11
  • 31
  • 47
jimwan
  • 1,086
  • 2
  • 24
  • 39
  • 1
    possible duplicate of [How do I create automatically a instance of every class in a directory?](http://stackoverflow.com/questions/11470291/how-do-i-create-automatically-a-instance-of-every-class-in-a-directory) – Anand Shah May 27 '13 at 15:46

1 Answers1

1

Just require the filename without the .rb extension like so:

require './test'

Suppose you have this directory structure:

+-- project/
|   |
|   +-- folder1/
|   |   |
|   |   +-- file1.rb
|   |
|   +-- folder2/
|       |
|       +-- file2.rb
|
+-- file3.rb

in this case you may want to add specific directories to the load path like so:

# in file3.rb
$LOAD_PATH.unshift './folder1'

this way you can require files by their name without specifying the folder every time:

require 'file1'

Now for the second part, getting an instance. You could just do AAA.new but i suppose you want to dynamically create instances of classes that are subclasses of TestCase. First you have to find all subclasses of TestCase:

class Class
  def subclasses
    constants.map do |c|
      const_get(c) 
    end.select do |c|
      c.is_a? Class
    end
  end
end

this will enable you to get a list of subclasses like so:

TestCase.subclasses
#=> [TestCase::AAA]

from which you can construct your objects

TestCase.subclasses.map{|klass| klass.new }
#=> [#<TestCase::AAA:0x007fc8296b07f8>]

or even shorter if you do not need to pass arguments to new

TestCase.subclasses.map(&:new)
#=> [#<TestCase::AAA:0x007fc8296b07d0>]

So far, so good. But if i get this right you are trying to build a test runner. Don't. There are plenty of testing libraries and great test runners out there. Ruby has the built-in Minitest and this blog post explains very well how you can best run your tests.

Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168