RSpec test for rake task

1.3k views Asked by At

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.

lib/tasks/todo.rake

namespace :todo do
  desc "delete items older than 7 days"
  task delete_items: :environment do
    Item.where("created_at <= ?", Time.now - 7.days).destroy_all
  end
end

spec/tasks/delete_items_task_spec.rb

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
2

There are 2 answers

0
jsookiki On BEST ANSWER

A couple things.
First off, you should put created_at in the create method: user.items.create(description: "Old Item", created_at: 12.days.ago).

Second, you need to call user.reload in order for the changes from your rake task to be available. So it should look like this: user.reload expect(user.items.count).to eq 1 etc

0
Kristján On

You haven't saved old_item after you set created_at = 12.days.ago, so in the database, it was still created just now. Add a save, use update_attributes(created_at: 12.days.ago), or I'm pretty sure you can just include created_at in the create attributes.