GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

Process Jobs Inline when Running Acceptance Tests

Web apps often move long-running processes (such as delivering email) out of the request/response cycle into a queue of background jobs. A worker process then picks up those jobs from the queue and runs them in the background.

In acceptance tests, it’s desirable to run those background jobs immediately, skipping the queueing component, to avoid writing custom code to work the jobs off.

Configure RSpec request specs with a custom run_background_jobs_immediately method:

RSpec.configure do |config|
  # if you're using Capybara 1.x, :feature should be replaced with :request
  config.around(:each, type: :feature) do |example|
    run_background_jobs_immediately do
      example.run
    end
  end

  config.include BackgroundJobs
end

A Delayed::Job implementation of the method:

# spec/support/background_jobs.rb
module BackgroundJobs
  def run_background_jobs_immediately
    delay_jobs = Delayed::Worker.delay_jobs
    Delayed::Worker.delay_jobs = false
    yield
    Delayed::Worker.delay_jobs = delay_jobs
  end
end

A Resque implementation of the method:

# spec/support/background_jobs.rb
module BackgroundJobs
  def run_background_jobs_immediately
    inline = Resque.inline
    Resque.inline = true
    yield
    Resque.inline = inline
  end
end

Voilà.