2014-11-21 32 views
8

提前致謝! Sidekiq工作得很好,但我無法設法用Devise Async進行測試,還是應該說我無法測試後者?如何使用Sidekiq測試Devise Async?

根據Sidekiq的文檔,當測試模式設置爲假!時,給工作人員的任何工作被推送到同一個工作人員名爲jobs的數組中。所以測試這個數組的增加是微不足道的。

但是,與Devise Async一樣,雖然它的後端包括Sidekiq::Worker,但並不那麼簡單。這裏的事情,我想測試一個小清單:

  • Devise::Async::Backend::Sidekiq.jobs
  • Devise::Mailer.deliveries
  • ActionMailer::Base.deliveries
  • Devise::Async::Backend::Worker.jobs

這些測試受試者均未點大小的增加。由於Devise以模型回調的形式發送它的電子郵件,我試圖在模型和控制器規範中進行測試。使用Factory Girl和Database Cleaner,我也嘗試了兩種模式:事務和截斷。不用說,我也嘗試了Sidekiq的兩種模式:假的!和內聯!

我錯過了什麼?

回答

1

正如documentation提到的,你可以檢查隊列大小

Sidekiq::Extensions::DelayedMailer.jobs.size 
+0

我嘗試了許多東西。謝謝! – kmanzana 2015-10-06 21:41:32

0

正在研究這個問題,碰上了通過,我認爲可能是在測試中色器件,異步還是很有幫助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 ,水豚 /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 

你會注意到,在這個測試實施

  1. 將導致sidekiq去運行排隊它的工作,
  2. 用戶模型郵件屬性必須被稱爲email或者你可以只更換上面的代碼。
  3. ActionMailer::Base.deliveries.map(&:to).flatten.count(user.email) == 1檢查,看的ActionMailer :: Base.deliveries被輸送到user.email