[英]Store emails in ActionMailer::Base.deliveries array when testing with Rspec
[英]Why are emails not getting in the ActionMailer::Base.deliveries table?
目前在我的開發環境中,在使用mail
后,我在ActionMailer::Base.deliveries
表中沒有看到任何內容。 我缺少一個設置嗎?
配置/環境/ development.rb:
config.action_mailer.delivery_method = :test
。
應用程序/郵寄者/ notifier.rb
def send_email(user)
mail(:to => user.email, :subject => "Welcome to our website!")
end
這些是我正在運行的測試:
When /^I signup$/ do
visit signup_path
@user = FactoryGirl.build(:user)
fill_in "user_email", :with => @user.email
fill_in "user_password", :with => @user.password
click_button "Join now"
end
Then /^I should receive a confirmation email$/ do
email = ActionMailer::Base.deliveries.last
email.subject.should == "Welcome to our website!"
end
現在我收到以下錯誤, I should receive a confirmation email
步驟: undefined method subject for nil:NilClass (NoMethodError)
謝謝!
另一種可能是在config / environments / test.rb中你有
config.action_mailer.delivery_method = :test
但你已經設定好了
config.action_mailer.perform_deliveries = false
所以改為
config.action_mailer.perform_deliveries = true
在我的情況下讓它再次起作用。
老問題,我知道,但有幾件事情浮現在腦海中:
您談論了開發環境的配置( config/environments/development.rb
),但這是您的測試不起作用。 檢查config/environments/test.rb
和config\\application.rb
。
我實際上想在我的開發環境中看到電子郵件陣列,但它總是在控制台中返回nil。 我終於意識到,因為數組只是一個內存對象而不是數據庫,所以控制台( rails c
)無法看到服務器中的內容( rails s
)。 當我將<%= ActionMailer::Base.deliveries.count %>
到視圖中時,我可以立即看到在開發中填充了數組。
如果您使用單獨的線程或任務發送電子郵件,則會出現另一個“我無法從控制台看到該過程”的情況。 使用delayed_job
,我發現這個答案表明你可以使用Delayed::Job.last.handler
查看作業(而不是實際的電子郵件),它確實查看了數據庫,因此可以跨進程工作。 但是,這僅在作業仍在數據庫中時工作,即在工作人員處理之前。
你得到的錯誤說電子郵件是零。 換句話說,deliveries.last方法返回nil,因為其中沒有電子郵件。
可能有很多原因......我假設您使用黃瓜作為測試機制?
1.驗證“click_button”是否提交
您可以嘗試輸入puts或log語句。 確保在運行黃瓜功能時實際打印。 有時這些東西不起作用,因為前端邏輯不起作用,測試失敗正確。 換句話說,您希望被觸發的控制器端點未被觸發。
2.使用單元測試驗證'send_email'是否正確
接下來,驗證您實際上是在發送電子郵件。 編寫單元測試以驗證其是否有效。 這應該快速而容易地開始。 那里有很多文章。
最后,並沒有真正相關,但你可能想要使用電子郵件規范 ,這應該提供一些不錯的測試方法,所以你不必重新發明輪子。
在做出由@Dominik Steiner回答的更改之后,如果它仍然無效,
另一種可能是在config / initializers / mailer.rb中,你應該有:
ActionMailer::Base.delivery_method = :test
在我的情況下,上面缺少,現在它工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.