ruby-on-rails - 使用 rspec 进行 ActionMailer 测试

标签 ruby-on-rails email rspec actionmailer

关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

6年前关闭。




Improve this question




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

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

请教我如何测试 ActionMailer使用 shouldarspec .

最佳答案

如何使用 RSpec 测试 ActionMailer

  • 适用于 Rails 3 和 4
  • 此信息取自 good tutorial

  • 假设以下 Notifier postman 和 User模型:
    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
    

    这些规范应该可以满足您的需求:
    # 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 提供有关此主题的原始博客文章的 Prop 。

    关于ruby-on-rails - 使用 rspec 进行 ActionMailer 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19983221/

    相关文章:

    ruby-on-rails - RSpec的should_receive和should_not_receive都通过了异常传递

    ruby-on-rails - 使用RSpec测试布局

    ruby-on-rails - 数组的所有变体

    ruby-on-rails - 将当前路径与 capybara 和 rspec 进行比较时出错

    django - Django,在模板中显示ValidationError

    java - 以 HTML 格式发送电子邮件内容

    ruby-on-rails - 使用 Capybara 检查复选框

    ruby-on-rails - 从 rmagick 图像创建回形针附件

    ruby-on-rails - Ruby 哈希长度或大小不返回任何内容

    c# - 从 .NET 中的数据库图像列将多个文件附加到电子邮件