简体   繁体   中英

Can Rake run each test in a separate Ruby instance?

I have a very simple Rakefile to test a small Ruby gem. It looks like this:

Rake::TestTask.new
task :default => :test

It invokes two tests that define constants with the same name. This results in errors being output by the second test like this:

warning: already initialized constant xxxxx

The reason for this is because Rake executes all of the tests within a single Ruby instance:

/usr/bin/ruby -I"lib" -I"/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib" "/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/rake_test_loader.rb" "test/test*.rb"

How should I specify that each test should be run in a separate Ruby instance ?

I have achieved this as shown below but I wonder if there is a better way because this solution doesn't scale well for lots of tests.

Rake::TestTask.new(:one) { |t| t.test_files = %w(test/test_one.rb) }
Rake::TestTask.new(:two) { |t| t.test_files = %w(test/test_two.rb) }
task :default => [:one, :two]

Instead of using Rake::TestTask , you could define a test task in your Rakefile that loops through each test file and runs them with sh like this:

task :test do
  libs = ['lib', 
          '/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib', 
          '/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/rake_test_loader.rb']
  test_files = FileList['test/**/test*.rb']

  test_files.each do |test_file|
    includes = libs.map { |l| "-I#{l}"}.join ' '
    sh "ruby #{includes} #{test_file}"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM