用rspec进行ActionMailer测试 [英] ActionMailer testing with rspec

查看:157
本文介绍了用rspec进行ActionMailer测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个涉及发送/接收电子邮件的 Rails 4应用。例如,我在用户注册,用户评论和应用程序中的其他事件发送电子邮件。

I am developing a Rails 4 application which involves sending / receiving emails. For example, I send emails during user registration, user comment, and other events in the app.

我已经使用动作 mailer创建了所有电子邮件,我使用 rspec shoulda 进行测试。我需要测试邮件是否正确接收到正确的用户。我不知道如何测试行为。

I have created all emails using the action mailer, and I used rspec and shoulda for testing. I need to test if the mails are received correctly to the proper users. I don't know how to test the behavior.

请告诉我如何测试一个 ActionMailer 使用 shoulda rspec

Please show me how to test an ActionMailer using shoulda and rspec.

推荐答案

有一个好教程如何使用RSpec测试ActionMailer。这是我遵循的做法,并没有让我失望。

There is a good tutorial on how to test ActionMailer using RSpec. This is the practice I have followed and it hasn't failed me yet.

本教程将适用于Rails 3和4。

The tutorial will work for both Rails 3 and 4.

如果上述链接中的教程中断,以下是相关部分:

In case the tutorial in the link above breaks, here are the relevant parts:

假设以下通知程序 mailer和用户模型:

class Notifier < ActionMailer::Base
  default from: 'noreply@company.com'

  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

这些规范应该让你想要的: / p>

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: 'lucas@email.com' }
    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(['noreply@company.com'])
    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

支持Lucas Caton的原始博客这个话题。

Props to Lucas Caton for the original blog post on this topic.

这篇关于用rspec进行ActionMailer测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆