The answer that I've found is to use load
rather than require
(I thought I had tested this, but perhaps I was mistaken)
so:
require 'thor'
load File.join(Rails.root.join('lib/tasks/test_task.thor'))
문제
I'm trying to write a very basic rspec to for my Thor task, however when trying to require (or load) the task it fails, giving NoMethodError ('undefined method ...') for the various Thor class-level methods (desc, method_option, class_option etc)
require "spec_helper"
require Rails.root.join('lib/tasks/test_task.thor')
describe 'TestTask' do
it "is instantiated ok" do
TestTask.new
end
end
As you can see I'm testing in the environment of a rails app.
The thor task itself executes fine from the command line.
I've looked through the Thor specs, as suggested elsewhere (Where can I find good examples of testing a Thor script with RSpec?)
Any ideas?
해결책
The answer that I've found is to use load
rather than require
(I thought I had tested this, but perhaps I was mistaken)
so:
require 'thor'
load File.join(Rails.root.join('lib/tasks/test_task.thor'))
다른 팁
Create Thorfile
in the root directory. It'll be loaded each time thor command is run in the project.
# 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 }
This will load all thor files before running thor tasks.
Now load Thorfile in rails_helper.rb
:
# spec/rails_helper.rb
require 'thor'
load Rails.root.join('Thorfile')
Now you can test your task without loading task at the top like this:
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