Search code examples
rubyrubygemsrake

How can I run my rake tests twice on purpose?


I need to run my rake tests twice in order to test the caching system of my Ruby gem. Before both the tests run, I need to clear my app's cache with

require 'lib/gem_name'
Gem.cache.clear

Then I just need to run the test task twice. I've tried putting the above code at the top of my Rakefile and listing the test files two times in my rake task, but I receive cannot require such file errors due to the gem lib paths not being loaded properly.

I need an efficient way to run the test twice, rather than running the cache-emptying code in IRB and then running rake test two times on the command line.

My Rakefile looks like this:

require 'rake/testtask'

Rake::TestTask.new do |t|
  t.libs << 'test'
  t.test_files = FileList['tests/test_*.rb']
  t.loader = :testrb
end

desc 'Run gem tests'
task default: :test

Solution

  • With the help of @maxple's comments and @OneNeptune's answer I found a way to achieve what I want. In my modified Rakefile below I set up a new task to clear the cache, and then a new test task which empties the cache and runs the tests twice.

    require 'rake/testtask'
    
    desc 'Clear gem cache'
    task :clear_cache do
      lib = File.expand_path('../lib', __FILE__)
      $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
      require 'gem_name'
      Gem.cache.clear
    end
    
    desc 'Perform tests exactly once'
    Rake::TestTask.new(:run_tests) do |t|
      t.libs << 'test'
      t.test_files = FileList['tests/test_*.rb']
      t.loader = :testrb
    end
    
    desc 'Performs test setup and runs tests twice'
    task :test do
      Rake::Task['clear_cache'].execute
      Rake::Task['run_tests'].execute
      Rake::Task['run_tests'].execute
    end
    
    task default: :test