正在研究这个问题,偶然发现了一个由 gitlab 完成的漂亮实现,我认为这可能有助于测试通过 sidekiq 队列推送的设计异步或电子邮件。
spec_helper.rb
email_helpers.rb
通过添加这些行spec_helper.rb
# An inline mode that runs the job immediately instead of enqueuing it
require 'sidekiq/testing/inline'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.include EmailHelpers
# other configurations line
end
并添加/spec/support/email_helpers.rb
module EmailHelpers
def sent_to_user?(user)
ActionMailer::Base.deliveries.map(&:to).flatten.count(user.email) == 1
end
def should_email(user)
expect(sent_to_user?(user)).to be_truthy
end
def should_not_email(user)
expect(sent_to_user?(user)).to be_falsey
end
end
要运行测试,例如测试您忘记的密码,我假设您知道 rspec、factorygirl、capybara
/spec/features/password_reset_spec.rb
require 'rails_helper'
feature 'Password reset', js: true do
describe 'sending' do
it 'reset instructions' do
#FactoryGirl create
user = create(:user)
forgot_password(user)
expect(current_path).to eq(root_path)
expect(page).to have_content('You will receive an email in a few minutes')
should_email(user)
end
end
def forgot_password(user)
visit '/user/login'
click_on 'Forgot password?'
fill_in 'user[email]', with: user.email
click_on 'Reset my password'
user.reload
end
end
你会注意到在这个测试实现中
- 将导致 sidekiq 运行作业而不是排队,
- 必须调用用户模型电子邮件属性,
email
或者您可以替换上面的代码。
ActionMailer::Base.deliveries.map(&:to).flatten.count(user.email) == 1
检查以查看 ActionMailer::Base.deliveries 正在交付给 user.email