集成测试ActionMailer和ActiveJob
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了集成测试ActionMailer和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
标记功能/场景,如果我想让作业真正执行的话。
以上是关于集成测试ActionMailer和ActiveJob的主要内容,如果未能解决你的问题,请参考以下文章
rspec 测试时,ActionMailer 方法调用在模块中返回 nil
Rails - 你如何测试 ActionMailer 在测试中发送了特定的电子邮件
问:如何使用 Turnip、capybara 和 Gherkin 测试 ActionMailer Deliver_later
Rails-如何测试ActionMailer发送了特定附件?