Alex Harvey
Alex Harvey

Reputation: 15482

Defer exceptions in multiple rake tasks

I am new to Rake.

I am writing a series of tests to validate data stored in YAML files. Each test is a separate rake task.

My problem is this: I would like a single exception to be raised at the end in the case of multiple test failures.

It seems like an easy problem but I'm afraid after much googling I can't find a clean way to do it.

One solution might be to use multiple begin, rescue blocks and a global variable?

status = 0

desc 'task 1'
task :task_1 do
  begin
    raise if something_is_bad
  rescue
    puts "something is bad"
    status += 1
  end
end

desc 'task 2'
task :task_2 do
  begin
    raise if something_else_is_bad
  rescue
    puts "something else is bad"
    status += 1
  end
end

desc 'default task'
task :default do
  Rake::Task['task_1'].execute
  Rake::Task['task_2'].execute
  if status
    raise "There were errors"
  end
end

That seems to result in too much repetition of begin, rescue.

Another solution might be to have an error handling method?

status = 0

def handle_failure(status, message)
  status += 1
  puts message
end

desc 'task 1'
task :task_1 do
  handle_failure(status, "something is bad") if something_is_bad
end

desc 'task 2'
task :task_2 do
  handle_failure(status, "something else is bad") if something_else_is_bad
end

desc 'default task'
task :default do
  Rake::Task['task_1'].execute
  Rake::Task['task_2'].execute
  if status
    raise "There were errors"
  end
end

I still feel there must be a better way?

Upvotes: 0

Views: 135

Answers (1)

ctide
ctide

Reputation: 5257

This is roughly how I would go about it, given your requirements.

desc 'task 1'
task :task_1 do
  if something_is_bad
    puts "something is bad"
    raise
  end
end



task :default do
  failed = false
  %W(task_1 task_2).each do |task|
    begin
      Rake::Task[task].execute
    rescue
      failed = true
    end
  end
  puts "One of the tasks failed!" if failed
end

Upvotes: 1

Related Questions