Search code examples
ruby-on-railsrubyrake-task

Rails 5, Why am I getting undefined constant when calling a class in a rake task?


I'm using Ruby on Rails 5.1.4, to make a little reporting system.

I'm using a Handler class like the following:

# app/handlers/report_handler.rb
class ReportHandler 
  ROLES = %w[admin staff]

  def self.queue_reports
    tennants = Tennant.elite

    tennants.each do |tennant|
      users = tennant.users.where(role: ROLES)
      users.each { |user| ReportMailer.monthly_report(user).deliver_later }
    end
  end
end

When using RSpec to test the class all my tests run green. but when I run my rake task it displays this error:

*** NameError Exception: uninitialized constant ReportHandler::Tennant

This is what my rake task looks like:

# lib/tasks/reports.rake
require './app/handlers/report_handler'

namespace :reports do
  # rake reports:send_monthly_reports
  desc "Send monthly reports to elite tennants"
  task :send_monthly_reports do
    ReportHandler.queue_reports
  end
end

I have no clue why my reports work when I call it from the my specs & console, but not from my rake task.


Solution

  • Turns out I wasn't loading My app's environment when running my rake task:

    Here's the fix:

    namespace :reports do
      desc "Send monthly reports to elite organizations"
      task send_monthly_reports: :environment do 
        ReportHandler.queue_reports
      end
    end