2015-06-16 37 views
9

我是RSpec和TDD的新手,我很難編寫RSpec測試來測試設計是否在用戶註冊後實際發送確認電子郵件。我知道我的應用程序按預期工作,因爲我已經在開發和生產環境中進行了物理測試。但是,我仍然需要爲此功能編寫RSpec測試,但我無法弄清楚如何通過RSpec測試發送確認電子郵件。RSpec測試設計郵件程序

factories/user.rb

FactoryGirl.define do 
    factory :user do 
    name "Jack Sparrow" 
    email { Faker::Internet.email } 
    password "helloworld" 
    password_confirmation "helloworld" 
    confirmed_at Time.now 
    end 
end 

spec/models/user_spec.rb

require 'rails_helper' 

RSpec.describe User, type: :model do 

    describe "user sign up" do 
    before do 
     @user = FactoryGirl.create(:user) 
    end 

    it "should save a user" do 
     expect(@user).to be_valid 
    end 

    it "should send the user an email" do 
     expect(ActionMailer::Base.deliveries.count).to eq 1 
    end 
    end 
end 

爲什麼設計後,我創建@user不發送確認電子郵件?我的測試返回ActionMailer :: Base.deliveries.count = 0.正如我所說,我是RSpec和TDD的新手,所以我完全錯過了這裏的東西?

+1

我猜電子郵件正在發送控制器創建動作,在這裏你只是創建一個新的用戶,並期待它發送一封電子郵件。因此,我會爲控制器創建操作編寫一個測試,並使用一些用戶屬性進行發佈,應該調用郵件程序。 – neo

+0

所以我需要在'registrations_controller_spec.rb'中寫入測試? –

+1

就是這樣,只要電子郵件從 – neo

回答

4

Devise使用自己的郵件程序,因此如果將測試放在正確的控制器文件本身不起作用,請嘗試Devise.mailer.deliveries而不是ActionMailer::Base.deliveries

+0

期望(Devise.mailer.deliveries.count).to到eq 1爲我工作,謝謝! – rmcsharry