Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing rake tasks with Rspec is not accepting arguments

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.

like image 564
x6iae Avatar asked Oct 12 '15 17:10

x6iae


2 Answers

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.

like image 61
x6iae Avatar answered Nov 06 '22 18:11

x6iae


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

like image 6
Jason Swett Avatar answered Nov 06 '22 20:11

Jason Swett