簡體   English   中英

在我的rspec中需要一個thor任務導致未定義的方法

[英]Requiring a thor task in my rspec results in undefined method

我正在嘗試為我的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任務本身從命令行執行得很好。

我已經按照其他地方的建議查看了Thor的規格( 我在哪里可以找到使用RSpec測試Thor腳本的好例子?

有任何想法嗎?

我發現的答案是使用load而不是require (我以為我測試了這個,但也許我錯了)

所以:

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

在根目錄中創建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加載rails_helper.rb

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM