17

I'm guessing this has to do with Rake reading the file once and not rewinding it? But, I'm not sure. Any ideas?

require 'rake'
require 'rails_helper'

describe 'MyRakeTask' do

  before(:all) do
    Rails.application.load_tasks
  end

  it 'does something sweet' do
    Rake::Task["namespace:my_task"].invoke # runs task
  end

  it 'but it doesnt do it again' do
    Rake::Task["namespace:my_task"].invoke # returns nil
  end

end
daino3
  • 4,386
  • 37
  • 48

1 Answers1

33

The Rake docs say invoke will only run the task if it's "needed". The following was pulled from another SO answer and might help clarify:

  • Rake::Task["build"].execute always executes the task, but it doesn't execute its dependencies

  • Rake::Task["build"].invoke executes the dependencies, but it only executes the task if it has not already been invoked

  • Rake::Task["build"].reenable first resets the task's already_invoked state, allowing the task to then be executed again, dependencies and all.

Community
  • 1
  • 1
eeeeeean
  • 1,774
  • 1
  • 17
  • 31
  • 2
    Thank you!! The `reenable` was what did it. – daino3 Sep 03 '15 at 19:12
  • This is handy (`.reenable`) when one task invokes another task. (Not the best design perhaps, but it is what it is) This works fine in the real world, where the other task has never been run. But in rspec, the other task is very likely already run in another test, so won't run when re-invoked by another task. I could have reenabled it in rspec, but it felt cleaner (and mostly harmless) to do it directly in the task code. – David Hempy Apr 13 '22 at 14:10