title: RSpec test for rake task
body: <p>I have created a custom rake task that deletes all items that are >= 7 days old.  I am trying to write a RSpec test for this new task but it seems like my task isn't really running in the test.  I have tested the task manually and it works as expected but I cannot seem to get the RSpec test to work.  I am fairly new to RSpec.</p>
  
  <p>lib/tasks/todo.rake</p>
  
  <pre><code>namespace :todo do
    desc "delete items older than 7 days"
    task delete_items: :environment do
      Item.where("created_at &lt;= ?", Time.now - 7.days).destroy_all
    end
  end
  </code></pre>
  
  <p>spec/tasks/delete_items_task_spec.rb</p>
  
  <pre><code>require 'rails_helper'
  require 'rake'
  
  describe "todo namespace rake delete_items task" do
  
    before do
      MyApp::Application.load_tasks
      Rake::Task.define_task(:environment)
    end
  
    let(:user) { FactoryGirl.create(:user) }
  
    it "should delete all items older than 7 days" do
  
      new_item = user.items.create(description: "New item")
      old_item = user.items.create(description: "Old item")
  
      old_item.created_at = 12.days.ago
  
      expect(new_item.days_left).to eq 7
      expect(old_item.days_left).to eq -5
  
      Rake::Task["todo:delete_items"].invoke
  
      # this is returning count = 2 which means old_item is not being deleted
      expect(user.items.count).to eq 1
      expect(user.items).to include(new_item)
      expect(user.items).not_to include(old_item)
  
    end
  end
  </code></pre>