我正在尝试对一些运行测试文件的测试进行元编程。 我想为每个文件创建一个测试类。 每个类都应该将文件名作为类变量或等效文件,以便它在正确的文件上执行测试。但是,我无法找到一种方法来为每个类别区分这些变量。在我当前的代码中,所有都将具有相同的类变量。 我怎样才能做到这一点?
module SomeFileTest
# create a test class for every profile
Dir.glob(File.dirname(__FILE__) + '/*.json') do |file|
# test class
test_class = Class.new(MiniTest::Unit::TestCase) do
# this var should be the #{file} var for each iteration
@@filename = file
@json
def setup
begin
@json = JSON.parse(File.read(@@filename))
rescue JSON::ParserError
assert(@json != nil, "JSON structure is not wellformed")
end
end
# test some things in te file
define_method("test_duplicates") do
# ...
end
end
# self-descriptive classname
filename = File.basename(file, ".json")
classname = "Test#{filename.capitalize}"
self.const_set(classname, test_class)
end
end
答案 0 :(得分:0)
我认为问题是@@filename
是一个类变量。在继承时,类变量在ruby中表现得有点直觉,这就是我通常避免它们的原因。试试这个:
module SomeFileTest
# create a test class for every profile
Dir.glob(File.dirname(__FILE__) + '/*.json') do |file|
# test class
test_class = Class.new(MiniTest::Unit::TestCase) do
# this var should be the #{file} var for each iteration
@filename = file
def self.filename
@filename
end
@json
def setup
begin
@json = JSON.parse(File.read(self.class.filename))
rescue JSON::ParserError
assert(@json != nil, "JSON structure is not wellformed")
end
end
# test some things in te file
define_method("test_duplicates") do
# ...
end
end
# self-descriptive classname
filename = File.basename(file, ".json")
classname = "Test#{filename.capitalize}"
self.const_set(classname, test_class)
end
end