操作邮件 link 签入 rspec

Action mailer link check in rspec

我在 rspec 测试中有这样的比较:

expect(new_mail.body.encoded).to match(url_for(controller:'some_controller',action:'some_action',some_param:some_param))

但它失败了,因为 ActionMailer 将 html 正文编码为如下内容:

   +<a href=3D"http://localhost:3000/some_controller/some_action/wgt1p468ersmkq=
   +gbvmfv5wgmifj13u894dfjrhc0hzczk71pcw3hrk5907iqfolc6onhxvik6apuuwgm1rng7ro=
   +rt8qih43thql3spyp5ajjdugy9jvx0xc5hvpi015z" style=3D"display: inline-block=
   +; background-color: #71B344; color: #FFF; border-radius: 4px; font-weight=
   +: bold; text-decoration: none; padding: 6px 12px; white-space: nowrap">
   +        Go to Your Account
   +      </a>

如何比较邮件正文中预期的 link 和编码的 link?

您可以使用 new_mail.body.to_s 来获取非编码版本,如 Guide to Rails Testing 中所示。

您还可以使用 Capybara 对呈现的电子邮件(或 any html fragment)进行断言,如果您真的想确定其中是否存在 link,这比仅使用字符串匹配要好:

let(:email){ Capybara::Node::Simple.new(new_mail.body.to_s) }

it "has a link" do
  url = url_for(controller:'some_controller',action:'some_action',some_param:some_param)
  expect(email).to have_link('A link', href: url)
end

已添加:

从多部分电子邮件中获取正确的部分:

def get_message_part(mail, content_type)
  mail.body.parts.find { |p| p.content_type.match content_type }.body.raw_source
end

let(:email) { Capybara::Node::Simple.new(get_message_part(new_mail, /html/)) }