Search code examples
ruby-on-railsrubyrspecrake

How to invoke RSpec inside a rake task?


We wrote some tests that are necessary, but very slow. So we configured RSpec to exclude them except on Solano, where we set up an ENV variable.

# spec_helper
unless ENV['RUN_ALL_TESTS'] == 'true'
  config.filter_run_excluding :slow
end

That works, but I'm trying to write a rake task we can call to run every test locally by setting that same ENV variable and then running the suite. I'm having trouble figuring out how to trigger RSpec. This is what I've got now:

# all_tests.rake
require 'rspec/core/rake_task'

desc 'Run all tests, even those usually excluded.'
task all_tests: :environment do
  ENV['RUN_ALL_TESTS'] = 'true'
  RSpec::Core::RakeTask.new(:spec)
end

When I run it, it doesn't run any tests.

Most of the stuff I found is for triggering a rake task inside of a test, testing a rake task, or setting up a Rakefile. We're using rspec-rails, our default rake task is already set up.


Solution

  • To run RSpec through its rake integration, you need to both define a task and invoke it:

    # all_tests.rake
    require 'rspec/core/rake_task'
    
    # Define the "spec" task, at task load time rather than inside another task
    RSpec::Core::RakeTask.new(:spec)
    
    desc 'Run all tests, even those usually excluded.'
    task all_tests: :environment do
      ENV['RUN_ALL_TESTS'] = 'true'
      Rake::Task['spec'].invoke
    end
    

    Rake::Task['spec'].invoke did nothing when you tried it because rake turns a task name which is not a name of a defined task but is a file name into a Rake::FileTask, both on the command line and in Rake::Task. You had no 'spec' task defined, but you have a spec directory, so rake spec ran without error and did nothing.