Reputation: 4164
I am trying to write a Rspec test for one of my rake task, according to this post by Stephen Hagemann.
lib/tasks/retry.rake
:
namespace :retry do
task :message, [:message_id] => [:environment] do |t, args|
TextMessage.new.resend!(args[:message_id])
end
end
spec/tasks/retry_spec.rb
:
require 'rails_helper'
require 'rake'
describe 'retry namespace rake task' do
describe 'retry:message' do
before do
load File.expand_path("../../../lib/tasks/retry.rake", __FILE__)
Rake::Task.define_task(:environment)
end
it 'should call the resend action on the message with the specified message_id' do
message_id = "5"
expect_any_instance_of(TextMessage).to receive(:resend!).with message_id
Rake::Task["retry:message[#{message_id}]"].invoke
end
end
end
However, when I run this test, I am getting the following error:
Don't know how to build task 'retry:message[5]'
On the other hand, when I run the task with no argument as:
Rake::Task["retry:message"].invoke
I am able to get the rake task invoked, but the test fails as there is no message_id
.
What is wrong with the way I'm passing in the argument into the rake task?
Thanks for all help.
Upvotes: 7
Views: 5485
Reputation: 231
Update from year 2023
You can try like below
Rake::Task['retry:message'].execute(Rake::TaskArguments.new([:message_id], ['900000']))
Upvotes: 0
Reputation: 4164
So, according to this and this, the following are some ways of calling rake tasks with arguments:
Rake.application.invoke_task("my_task[arguments]")
or
Rake::Task["my_task"].invoke(arguments)
On the other hand, I was calling the task as:
Rake::Task["my_task[arguments]"].invoke
Which was a Mis combination of the above two methods.
A big thank you
to Jason for his contribution and suggestion.
Upvotes: 15
Reputation: 45094
In my opinion, rake tasks shouldn't do things, they should only call things. I never write specs for my rake tasks, only the things they call.
Since your rake task appears to be a one-liner (as rake tasks should be, IMO), I wouldn't write a spec for it. If it were more than one line, I would move that code somewhere else to make it a one-liner.
But if you insist on writing a spec, maybe try this: Rake::Task["'retry:message[5]'"].invoke
(added single quotes).
Upvotes: 6