title: Rails Rake Task - Access to model class
body: <p>I would like to define a Ruby (1.9.2)-on-Rails(3.0.5) rake task which adds a user to the User table. The file looks like this:</p>
  
  <pre><code>#lib/tasks/defaultuser.rake
  require 'rake'
  namespace :defaultuser do
    task :adduser do 
      u=User.new
      u.email="bob@example.com"
      u.password="password"
      u.save
      u.errors.each{|e| p e}
    end
  end
  </code></pre>
  
  <p>I would then invoke the task as </p>
  
  <pre><code>&gt; rake defaultuser:adduser
  </code></pre>
  
  <p>I tested the code in the :adduser task in the Rails console, and it works fine. 
  I tested the rake task, running only </p>
  
  <pre><code>print "defaultuser:adduser"
  </code></pre>
  
  <p>in the body of the task, and it worked fine. </p>
  
  <p>However, when I combined them, it complained, saying </p>
  
  <pre><code>rake aborted!
  uninitialized constant User
  </code></pre>
  
  <p>I tried a </p>
  
  <pre><code>require File.expand_path('../../../app/models/user.rb', __FILE__)
  </code></pre>
  
  <p>at above the namespace definition in the rake file, but that didn't work. I got</p>
  
  <pre><code>rake aborted!
  ActiveRecord::ConnectionNotEstablished
  </code></pre>
  
  <p>What do I need to do so that I have the same access to the User model class in the Rake task that I have in the Rails console?</p>