Just some notes on using rake (Ruby Make) tasks.
See also https://ruby.github.io/rake/
This is one approach to testing a rake task. Another might be to encapsulate the task in a module and test that. That wouldn’t quite be a complete, but it might be enough is some cases.
require "rake"
RSpec.describe 'projects:todos' do
before do
load File.expand_path('../../../../lib/tasks/projects/todos.rake', __FILE__)
Rake::Task.define_task :environment
end
subject do
Rake::Task['projects:todos']
end
it 'puts projects to stdout' do
expect { subject.execute }.to output(
"Project One"
"- [X] Todo Item 1"
"- [ ] Todo Item 2"
"- [ ] Todo Item 3"
""
"Project Two"
"- [ ] Todo Item 1"
).to_stdout
end
end
$ rails g task_namespace task_one task_two
will produce lib/tasks/task_namespace.rake
:
namespace :task_namespace do
desc "TODO"
task task_one: :environment do
end
desc "TODO"
task task_two: :environment do
end
end
In this example, the task depends on the environment
task. For rails, I
think this loads the environment as specified in config/environment.rb
$ rake -T
- Write a good description
- Namespace task related tasks
- Use folder structure to group related tasks (ie, one task per file)
- Extract task logic to modules
- Provide useful output to stdout like start, progress and results
- Write logs
Force a 0 exit code
sh "the command || true"
or pass an empty block
sh "your shell command" do |ok,res|
end
namespace :foo do
desc 'Seed flag rules with several conditions each'
task :bar, %i[arg1 arg2] => :environment do |_t, args|
arg1 = args[:arg1]
arg2 = args[:arg2]
# . . .
end
end
rake foo:bar[arg1,arg2]
When using zsh, the brackets need to be escaped. Prefix the above command
with noglob
.
require 'rake'
Rails.application.load_tasks
Rake::Task['my_task'].invoke