简体   繁体   中英

NameError: uninitialized constant Rails::TestTask

I put this code inside my Rakefile in order to be able to run tests from an additional folder "test/classes" (not just from test/models, test/controllers etc):

# 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"]

This code works perfectly when I run rails test .

But when I run rails db:migrate , I get this error:

NameError: uninitialized constant Rails::TestTask
/Users/Developer/project/Rakefile:11:in `block in <top (required)>'
/Users/Developer/project/Rakefile:9:in `<top (required)>'

What do I do to get rid of the error, but still be able to load test files from

insert

require 'rake/testtask'

into Rakefile

I saw this during a Rails 5.2 upgrade (from Rails 4.2). The fix for me was to rename Rails::TestTask to Rake::TestTask everywhere.

As of 2021

On your tests' setup, you can load your task:

before { Rails.application.load_tasks }

Then you invoke the task inside your test with:

Rake.application.invoke_task "namespace:task_name"

Sample code

Let's say you want to test the rake task below:

# 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

Can be tested with:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM