testing rake tasks with Rspec is not accepting arguments
Asked Answered
M

3

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.

Mattie answered 12/10, 2015 at 17:23 Comment(0)
M
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.

Mattie answered 13/10, 2015 at 14:18 Comment(0)
C
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).

Candleberry answered 12/10, 2015 at 17:43 Comment(1)
> rake tasks shouldn't do things, they should only call things. I never write specs for my rake tasks, only the things they call. +1Cazares
E
0

Update from year 2023

You can try like below

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

Earreach answered 19/6, 2023 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.