Search code examples
ruby-on-railsrake

custom rake task error


I'm trying to run a custom rake test. Here's the code:

task :test => :environment do
  user = User.first
  puts "Winner: #{user.email}"
  puts "test"
end

But when I run it, I get this error.

$ rake test

rake aborted!
undefined method `email' for nil:NilClass

Tasks: TOP => test
(See full trace by running task with --trace)

Any insight on why I don't have access to the class User? Even though I have :environment in there?


Solution

  • I ran in to something similar recently. I tried to get the id and I was not able to get this to work until I used a mapping. Try this:

    task :test => :environment do 
      email = User.first.map(&:email)
      puts "Winner: #{email}"
      puts "test" 
    end
    

    I am not saying this is the proper way to do it, but it worked for me.