7

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.

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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).

1 Comment

> rake tasks shouldn't do things, they should only call things. I never write specs for my rake tasks, only the things they call. +1
0

Update from year 2023

You can try like below

Rake::Task['retry:message'].execute(Rake::TaskArguments.new([:message_id], ['900000']))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.