RSpec tesiting for rake task [Ruby on Rails]

I summarized the procedure of the RSpec test in this article.
Since I summarized it as simple as possible, please read through those who are trying to create Rake task for the first time.


Creating a Rake task file

The following command creates a Rake task file in lib/tasks:

(Please change “report”.)

1
$ rails generate task report

Please write the following code in the above lib/tasks/report.rake:

1
2
3
4
5
6
7
8
9
10
namespace :report do
# desc is required
desc 'Generate report'
# : Environment is required to access Rails environment
task generate: :environment do
# Write something
ReportGenerator.generate
end
end

After the coding, you can execute rake report:generate command!

RSpec for rake task

Executing rake task in RSpec

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
require 'rails_helper'
require 'rake'
describe 'rake task reporting' do
before(:all) do
@rake = Rake::Application.new
Rake.application = @rake
Rake.application.rake_require 'tasks/report' # Point 1
Rake::Task.define_task(:environment)
end
before(:each) do
@rake[task].reenable # Point 2
end
describe 'report:generate' do
let(:task) { 'report:generate' }
it 'is succeed' do
expect(@rake[task].invoke).to be_truthy
end
end
end

Executing model method

1
2
3
4
5
6
namespace :report
desc 'Generate report'
it 'generates report' do
# do something
end
end

It’s so simple to execute unit testing.
In addition, if you type ReportGenerator.generate on rails console, you can also perform exactly the same processing as the Rake task.

Special Thanks