名称错误:未初始化常量Rails :: TestTask

4

我将这段代码放在我的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)>'

我应该怎么做才能消除错误,同时仍然能够加载测试文件?

3个回答

9

插入

require 'rake/testtask'

转换为 Rakefile


1
我不得不这样做,并且像@pdobb建议的那样将Rails :: TestTask重命名为Rake :: TestTask - andyrue

4

我在进行Rails 5.2升级(从Rails 4.2)时遇到了这个问题。对我来说,解决方法是将Rails::TestTask重命名为Rake::TestTask


0

截至2021年

在您的测试设置中,您可以加载您的任务:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接