Testing emails with Capybara, Rspec, ActiveJob, and Sidekiq

I’m sharing this because it was really not obvious what’s happening with tests that verify emails when using the new ActiveJob interface.

Basically, if you set the following in your test.rb, then sidekiq does not come into play, at all.

  config.active_job.queue_adapter = :test

Next, ActiveJob does not process emails when the emails are to be sent as a result of Capybara integration tests.

The fix is to create a file in spec/support/perform_enqueued.rb with the following (or add to your rails_helper.rb):

# From http://stackoverflow.com/a/29967430/1009332
RSpec.configure do |config|
  config.before :example, perform_enqueued: true do
    @old_perform_enqueued_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_jobs
    @old_perform_enqueued_at_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
  end

  config.after :example, perform_enqueued: true do
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
  end
end

I had to add this to all integration tests depending on the processing of jobs, including sending of emails.

1 Like