0

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]
starfry
  • 9,273
  • 7
  • 66
  • 96
  • Maybe it's easier to change the tests so they can run with the default setup. Move the constant definition into a helper file or define it under your test's namespace. – Stefan Nov 24 '14 at 11:14
  • The easiest thing for me is to go with the above as I only have two tests. I hoped the question would reveal a better way of doing it, though, just in case I'd missed something trivial. It's a one-off scenario where there are two versions of the same stand-alone script and it isn't worth refactoring just to fix this specific issue. The tests are in a gem called `afsplitter` that I've put on rubygems if you're interested in the context. – starfry Nov 28 '14 at 11:43
  • You should use a test suite like [minitest](https://github.com/seattlerb/minitest) – Stefan Nov 28 '14 at 12:03

1 Answers1

0

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