user1351104
user1351104

Reputation:

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

Upvotes: 0

Views: 140

Answers (2)

user1351104
user1351104

Reputation:

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

Upvotes: 0

OneNeptune
OneNeptune

Reputation: 913

You can either reenable the task like:

task :test do |task|
    task.execute 1
    task.execute 2
    task.execute 3
end

which is superior to reenable since reenable would look like this:

task :test do |task|
    task.invoke 1
    task.reenable
    task.invoke 2
    task.reenable
    task.invoke 3
end

You can read more about execute vs invoke here: https://blog.simplificator.com/2014/12/30/rake-execute-vs-invoke/

Upvotes: 1

Related Questions