Ruby-on-rails 使用 rspec 进行 ActionMailer 测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19983221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ActionMailer testing with rspec
提问by Dinkaran Ilango
I am developing a Rails 4 applicationwhich involves sending / receiving emails. For example, I send emails during user registration, user comment, and other events in the app.
我正在开发一个涉及发送/接收电子邮件的Rails 4 应用程序。例如,我在用户注册、用户评论和应用程序中的其他事件期间发送电子邮件。
I have created all emails using the action mailer, and I used rspecand shouldafor testing. I need to test if the mails are received correctly to the proper users. I don't know how to test the behavior.
我已经使用 action 创建了所有电子邮件mailer,并且我使用rspec和shoulda进行测试。我需要测试邮件是否正确接收到正确的用户。我不知道如何测试行为。
Please show me how to test an ActionMailerusing shouldaand rspec.
请告诉我如何测试ActionMailer使用shoulda和rspec。
回答by CDub
How to test ActionMailer with RSpec
如何使用 RSpec 测试 ActionMailer
- works for Rails 3 and 4
- this information has been taken from a good tutorial
- 适用于 Rails 3 和 4
- 此信息取自一个很好的教程
Assuming the following Notifiermailer and Usermodel:
假设以下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
And the following test configuration:
以及以下测试配置:
# config/environments/test.rb
AppName::Application.configure do
config.action_mailer.delivery_method = :test
end
These specs should get you what you want:
这些规格应该可以满足您的需求:
# 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
Props to Lucas Caton for the original blog post on this topic.
为 Lucas Caton 提供有关此主题的原始博客文章的道具。

