在 rails 作业上禁用 ruby 以进行测试

Disable ruby on rails job for test

我正在用 rspec 编写控制器测试,在操作完成后,我的工作应该向管理员用户发送电子邮件。但我想为我的测试禁用这项工作或以某种方式模拟它。我该怎么做?

我正在使用 delayed_job_active_record + daemons 宝石。

class AdminNotificationJob < ActiveJob::Base
  queue_as :default

  def perform(method, parameter)
    User.admin.includes(:profile).each do |admin|
      AdminMailer.send(method, admin, parameter).deliver_later
    end
  end
end
#config/environment/test.rb
config.active_job.queue_adapter = :test

# in spec
expect { your_action_that_triggers_job_enqueuing }
  .to have_enqueued_job(AdminNotificationJob)
  .with(your_arguments)

您的控制器测试将如下所示:

it "enqueues a AdminNotification" do
  expect {
    get :your_controller_action, {}
  }.to have_enqueued_job(AdminNotificationJob)
end

这使用 #have_enqueued_job method found on rspec-rails