我正在開發一個Rails 4應用程序,其中涉及發送/接收電子郵件。例如,我在用戶註冊期間發送電子郵件,用戶評論以及應用中的其他事件。使用rspec的ActionMailer測試
我創建使用動作mailer
所有的電子郵件,我用rspec
和shoulda
進行測試。我需要測試郵件是否被正確接收到正確的用戶。我不知道如何測試行爲。
請告訴我如何使用shoulda
和rspec
測試ActionMailer
。
我正在開發一個Rails 4應用程序,其中涉及發送/接收電子郵件。例如,我在用戶註冊期間發送電子郵件,用戶評論以及應用中的其他事件。使用rspec的ActionMailer測試
我創建使用動作mailer
所有的電子郵件,我用rspec
和shoulda
進行測試。我需要測試郵件是否被正確接收到正確的用戶。我不知道如何測試行爲。
請告訴我如何使用shoulda
和rspec
測試ActionMailer
。
有關於如何使用RSpec測試ActionMailer的good tutorial。這是我遵循的做法,它並沒有讓我失望。
本教程將提供兩個軌道3和4
如果在上面休息的鏈接教程,下面給出相關部分:
假設下面的Notifier
郵件和User
型號:
class Notifier < ActionMailer::Base
default from: '[email protected]'
def instructions(user)
@name = user.name
@confirmation_url = confirmation_url(user)
mail to: user.email, subject: 'Instructions'
end
end
class User
def send_instructions
Notifier.instructions(self).deliver
end
end
和下面的測試配置:
# config/environments/test.rb
AppName::Application.configure do
config.action_mailer.delivery_method = :test
end
這些規格應該得到你想要的東西:
# spec/models/user_spec.rb
require 'spec_helper'
describe User do
let(:user) { User.make }
it "sends an email" do
expect { user.send_instructions }.to change { ActionMailer::Base.deliveries.count }.by(1)
end
end
# spec/mailers/notifier_spec.rb
require 'spec_helper'
describe Notifier do
describe 'instructions' do
let(:user) { mock_model User, name: 'Lucas', email: '[email protected]' }
let(:mail) { Notifier.instructions(user) }
it 'renders the subject' do
expect(mail.subject).to eql('Instructions')
end
it 'renders the receiver email' do
expect(mail.to).to eql([user.email])
end
it 'renders the sender email' do
expect(mail.from).to eql(['[email protected]'])
end
it 'assigns @name' do
expect(mail.body.encoded).to match(user.name)
end
it 'assigns @confirmation_url' do
expect(mail.body.encoded).to match("http://aplication_url/#{user.id}/confirmation")
end
end
end
道具盧卡斯卡頓關於這一主題的原始博客文章。
但是,如果你有任何問題,我們可以從User.send_instructions捕獲一個異常,並向自己發送一封包含異常的電子郵件。你只是測試是否發送了*任何*電子郵件,而不是你特定的電子郵件。 – Phillipp
@Phillipp提出了一個很好的觀點,如果你想測試特定的郵件,ActionMailer :: Base.deliveries是一個包含'Mail :: Message'對象的數組。請參閱[Mail :: Message API](http://www.rubydoc.info/github/mikel/mail/Mail/Message)。 – janechii
對於那些想知道爲什麼'mock_model'不起作用的人:http://stackoverflow.com/a/24060582/2899410 – 707
爲什麼地獄這個問題關閉作爲題外話? –