如何使用 Rspec 检查 ActiveJob 中排队的内容 [英] How to check what is queued in ActiveJob using Rspec
问题描述
我正在 Rails API 应用程序中研究 reset_password 方法.当这个端点被命中时,一个 ActiveJob 会排队,它将向 Mandrill(我们的交易电子邮件客户端)发出请求.我目前正在尝试编写测试以确保在命中控制器端点时 ActiveJob 正确排队.
I'm working on a reset_password method in a Rails API app. When this endpoint is hit, an ActiveJob is queued that will fire off a request to Mandrill (our transactional email client). I'm currently trying to write the tests to ensure that that the ActiveJob is queued correctly when the controller endpoint is hit.
def reset_password
@user = User.find_by(email: params[:user][:email])
@user.send_reset_password_instructions
end
send_reset_password_instructions 在创建 ActiveJob 之前创建一些 url 等,代码如下:
The send_reset_password_instructions creates some url's etc before creating the ActiveJob which's code is below:
class SendEmailJob < ActiveJob::Base
queue_as :default
def perform(message)
mandrill = Mandrill::API.new
mandrill.messages.send_template "reset-password", [], message
rescue Mandrill::Error => e
puts "A mandrill error occurred: #{e.class} - #{e.message}"
raise
end
end
目前我们没有为 ActiveJob 使用任何适配器,所以我只想通过 Rspec 检查 ActiveJob 是否已排队.
At the moment we are not using any adapters for the ActiveJob, so I just want to check with Rspec that the ActiveJob is queued.
目前我的测试看起来像这样(我使用 factory girl 创建用户):
Currently my test looks something like this (I'm using factory girl to create the user):
require 'active_job/test_helper'
describe '#reset_password' do
let(:user) { create :user }
it 'should create an ActiveJob to send the reset password email' do
expect(enqueued_jobs.size).to eq 0
post :reset_password, user: { email: user.email }
expect(enqueued_jobs.size).to eq 1
end
end
一切正常,我只需要创建测试!
Everything works in reality, I just need to create the tests!
我使用的是 ruby 2.1.2 和 rails 4.1.6.
I'm using ruby 2.1.2 and rails 4.1.6.
我无法在网络上的任何地方看到有关如何对此进行测试的任何文档或帮助,因此我们将不胜感激!
I can't see any documentation or help anywhere on the web on how to test on this so any help would be greatly appreciated!
推荐答案
接受的答案不再适合我,所以我在评论中尝试了 Michael H. 的建议,这很有效.
The accepted answer no longer works for me, so I tried Michael H.'s suggestion in the comments, which works.
describe 'whatever' do
include ActiveJob::TestHelper
after do
clear_enqueued_jobs
end
it 'should email' do
expect(enqueued_jobs.size).to eq(1)
end
end
这篇关于如何使用 Rspec 检查 ActiveJob 中排队的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!