[英]NameError: uninitialized constant Rails::TestTask
我將此代碼放在我的 Rakefile 中,以便能夠從附加文件夾“test/classes”(不僅僅是來自 test/models、test/controllers 等)運行測試:
# Adding test/classes directory to rake test.
namespace :test do # line 9
desc "Test tests/classes/* code"
Rails::TestTask.new(parsers: 'test:prepare') do |t| # line 11
t.pattern = 'test/classes/**/*_test.rb'
end
end
Rake::Task['test:run'].enhance ["test:classes"]
當我運行rails test
時,此代碼完美運行。
但是當我運行rails db:migrate
,我收到了這個錯誤:
NameError: uninitialized constant Rails::TestTask
/Users/Developer/project/Rakefile:11:in `block in <top (required)>'
/Users/Developer/project/Rakefile:9:in `<top (required)>'
我該怎么做才能擺脫錯誤,但仍然能夠從
插入
require 'rake/testtask'
進入Rakefile
我在Rails 5.2升級期間(從Rails 4.2)看到了這一點。 對我來說,修復是將Rails::TestTask
重命名為Rake::TestTask
。
在您的測試設置中,您可以加載您的任務:
before { Rails.application.load_tasks }
然后你在你的測試中調用任務:
Rake.application.invoke_task "namespace:task_name"
假設您要測試下面的 rake 任務:
# lib/tasks/notifications.rake
namespace :notifications do
desc "This task is called by the Heroku scheduler add-on"
task properties_created: :environment do
Account.all.each { |account| AccountMailer.properties_created(account).deliver } if Property.yesterday.any?
end
end
可以測試:
# test/tasks/notifications_test.rb
require "test_helper"
class NotificationsTest < ActiveSupport::TestCase
include ActionMailer::TestHelper
before { Rails.application.load_tasks }
it "does not send email if no property created yesterday" do
account = create(:account)
create(:property, created_at: 2.days.ago, account: account)
assert_emails(0) { Rake.application.invoke_task "notifications:properties_created" }
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.