Rails ActionMailer 附件留空

eir*_*kir 3 ruby-on-rails actionmailer html-email email-attachments ruby-on-rails-3

我正在尝试使用 ActionMailer 生成的电子邮件发送内嵌附件(图像)。但是,每次添加附件时,我都会收到空白的电子邮件正文。我尝试生成一个简单的测试电子邮件来消除其他变量,但我一直遇到同样的问题。

我正在使用 Rails 3.2.13,以下是我的代码和失败的规范:

应用程序/邮件/contact_mailer.rb

class ContactMailer < ActionMailer::Base
  default from: "support@example.com"

  def test
    attachments.inline['logo.png'] = File.read Rails.root.join('app/assets/images/emails/logo.png').to_s
    mail(to: 'my_email@gmail.com', subject: 'Testing, Testing')
  end

  def test_no_attachment
    mail(to: 'my_email@gmail.com', subject: 'Testing, Testing')
  end
Run Code Online (Sandbox Code Playgroud)

应用程序/视图/contact_mailer/test.html.erb

<p>This is a test.</p>
<p>This is only a test.</p>
<%= image_tag attachments['mhbo_logo.png'].url %>
Run Code Online (Sandbox Code Playgroud)

应用程序/视图/contact_mailer/test_no_attachment.html.erb

<p>This is a test.</p>
<p>This is only a test.</p>
Run Code Online (Sandbox Code Playgroud)

规格/邮件/contact_mailer_spec.rb

require 'spec_helper'

describe ContactMailer do
  describe 'test' do
    it 'should send' do
      ContactMailer.test.deliver
      ActionMailer::Base.deliveries.count.should eq 1
      ActionMailer::Base.deliveries.last.body.should match /This is a test./
    end
  end

  describe 'test_no_attachment' do
    it 'should send' do
      ContactMailer.test_no_attachment.deliver
      ActionMailer::Base.deliveries.count.should eq 1
      ActionMailer::Base.deliveries.last.body.should match /This is a test./
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

第二个测试通过,但第一个测试失败,并显示以下内容:

 Failure/Error: ActionMailer::Base.deliveries.last.body.should match /This is a test./
   expected  to match /This is a test./
 # ./spec/mailers/contact_mailer_spec.rb:8:in `block (3 levels) in <top (required)>'
Run Code Online (Sandbox Code Playgroud)

因此,这封电子邮件的正文是空白的。

我的代码可能有什么问题?还是我测试这个的方式有问题?我已经用相同的语法测试了许多其他电子邮件,但没有授予任何附件。我也很困惑,因为我认为添加附件会发送多部分电子邮件,所以它ActionMailer::Base.deliveries.count会大于 1。我错了吗?

我在这里有点迷茫,所以任何和所有的帮助都将不胜感激。

eir*_*kir 6

事实证明,我错误地测试了电子邮件内容。多部分电子邮件(例如带有附件的电子邮件)作为单个电子邮件发送,但包含多个部分,访问方式如下:

ActionMailer::Base.deliveries.last.body.parts
Run Code Online (Sandbox Code Playgroud)

所以,为了找到HTML body对应的部分,我写了这个测试:

ActionMailer::Base.deliveries.last.body.parts.detect{|p| p.content_type.match(/text\/html/)}.body.should match /This is a test./
Run Code Online (Sandbox Code Playgroud)

我将此代码重构为一个宏,以使我的测试更具可读性:

规范/宏/testing_macros.rb

module TestingMacros
  def last_email_html_body
    ActionMailer::Base.deliveries.last.body.parts.detect{|p| p.content_type.match(/text\/html/)}.body
  end
end
Run Code Online (Sandbox Code Playgroud)

规格/邮件/contact_mailer_spec.rb

…
last_email_html_body.should match /This is a test./
…
Run Code Online (Sandbox Code Playgroud)