【问题标题】:Requiring a thor task in my rspec results in undefined method在我的 rspec 中需要一个雷神任务导致未定义的方法
【发布时间】:2014-02-28 19:32:05
【问题描述】:

我正在尝试为我的 Thor 任务编写一个非常基本的 rspec,但是当尝试要求(或加载)它失败的任务时,为各种 Thor 类提供 NoMethodError ('undefined method ...') -级别方法(desc、method_option、class_option 等)

require "spec_helper"
require Rails.root.join('lib/tasks/test_task.thor')

describe 'TestTask' do

  it "is instantiated ok" do
    TestTask.new
  end
end

如您所见,我正在 Rails 应用程序环境中进行测试。

thor 任务本身可以从命令行很好地执行。

按照其他地方的建议 (Where can I find good examples of testing a Thor script with RSpec?),我查看了 Thor 规格

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec thor


    【解决方案1】:

    在根目录下创建Thorfile。每次在项目中运行 thor 命令时都会加载它。

    # Thorfile
    # load rails environment for all thor tasks (optionally)
    ENV['RAILS_ENV'] ||= 'development'
    require File.expand_path('config/environment.rb')
    
    Dir["#{__dir__}/lib/tasks/*.thor"].sort.each { |f| load f }
    
    

    这将在运行 thor 任务之前加载所有 thor 文件。

    现在在rails_helper.rb中加载Thorfile:

    # spec/rails_helper.rb
    require 'thor'
    load Rails.root.join('Thorfile')
    

    现在您可以测试您的任务,而无需在顶部加载任务,如下所示:

    require "spec_helper"
    
    describe TestTask do
      subject { described_class.new }
    
      let(:run_task) { subject.invoke(:hello, [], my_option: 42) }
    
      it "runs" do
        expect { run_task }.not_to raise_error
      end
    end
    

    【讨论】:

      【解决方案2】:

      我找到的答案是使用load 而不是require (我以为我已经测试过了,但也许我弄错了)

      所以:

      require 'thor' load File.join(Rails.root.join('lib/tasks/test_task.thor'))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多