19

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

1 Answer 1

36

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.

2
  • 2
    Thank you!! The reenable was what did it.
    – daino3
    Sep 3, 2015 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. Apr 13, 2022 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.