使用 Rspec 测试 rake 任务不接受参数 [英] testing rake tasks with Rspec is not accepting arguments

查看:40
本文介绍了使用 Rspec 测试 rake 任务不接受参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 这篇由斯蒂芬·哈格曼 (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

我能够调用 rake 任务,但测试失败,因为没有 message_id.

I am able to get the rake task invoked, but the test fails as there is no message_id.

我将参数传递给 rake 任务的方式有什么问题?

What is wrong with the way I'm passing in the argument into the rake task?

感谢所有帮助.

推荐答案

所以,根据 this这个,下面是一些带参数调用rake任务的方法:

So, according to this and this, the following are some ways of calling rake tasks with arguments:

Rake.application.invoke_task("my_task[arguments]")

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.

非常感谢 Jason 的贡献和建议.

A big thank you to Jason for his contribution and suggestion.

这篇关于使用 Rspec 测试 rake 任务不接受参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆