集成测试 ActionMailer 和 ActiveJob

Integration testing ActionMailer and ActiveJob

过去,Rails 3,我已经将动作邮件程序测试与我的 Cucumber/Rspec-Capybara 测试集成在一起,如下例所示。对于 Rails 4,使用以下内容似乎不起作用。

我可以看到作业已使用 enqueued_jobs.size 排队。如何启动排队作业以确保正确生成电子邮件主题、收件人和正文?

app/controllers/robots_controller.rb

class MyController < ApplicationController
  def create
    if robot.create robot_params
      RobotMailer.hello_world(robot.id).deliver_later
      redirect_to robots_path, notice: 'New robot created'
    else
      render :new
    end
  end
end

spec/features/robot_spec.rb

feature 'Robots' do
  scenario 'create a new robot' do
    login user
    visit '/robots'
    click_link 'Add Robot'
    fill_in 'Name', with: 'Robbie'
    click_button 'Submit'

    expect(page).to have_content 'New robot created'

    new_robot_mail = ActionMailer::Base.deliveries.last
    expect(new_robot_mail.to) eq 'myemail@robots.com'
    expect(new_robot_mail.subject) eq "You've created a new robot named Robbie"
  end
end

我使用 rspec-activejob gem 和以下代码:

RSpec.configure do |config|
  config.include(RSpec::ActiveJob)

  # clean out the queue after each spec
  config.after(:each) do
    ActiveJob::Base.queue_adapter.enqueued_jobs = []
    ActiveJob::Base.queue_adapter.performed_jobs = []
  end

  config.around :each, perform_enqueued: true do |example|
    @old_perform_enqueued_jobs = ActiveJob::Base.queue_adapter.perform_enqueued_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = true
    example.run
    ActiveJob::Base.queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs
  end

  config.around :each, perform_enqueued_at: true do |example|
    @old_perform_enqueued_at_jobs =    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = true
    example.run
    ActiveJob::Base.queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs
  end
end

如果我想让作业实际执行,这让我可以用 perform_enqueued: true 标记 features/scenarios。