我如何从 ActionMailer 获取下游 rspec 测试的 link?

How do I grab a link for downstream rspec test from ActionMailer?

我正在构建一个生成邀请电子邮件的 integration/feature 测试,在 rspec 测试中,我希望能够获取 link 然后跟随它进行下游测试。

以下是我获取电子邮件的方式:

last_delivery = ActionMailer::Base.deliveries.last

正文显示如下:

puts last_delivery.body

----==_mimepart_54cc1b76a8d12_d673ffe1c74c22869b6
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit

<html>
  <body>
    <!DOCTYPE html>
<html>
  <head>
    <meta content='text/html; charset=UTF-8' http-equiv='Content-Type' />
  </head>
  <body>
    <h1>You have a pending invite!</h1>
    <p>To join, please follow the link below and login or signup.</p>
    <a href="http://localhost:3000/invite/13">Your Invite</a>
  </body>
</html>
  </body>
</html>

----==_mimepart_54cc1b76a8d12_d673ffe1c74c22869b6--

邀请的 ID 可能会在测试运行之间发生变化,所以这是否可能以及如何提取 link 以用于关注?

您可以尝试使用 Nokogiri 从 link:

中解析 url
doc = Nokogiri::HTML.parse(last_delivery.body)
url = doc.css("a").map { |link| link[:href] }.first

除了这种方法,为什么不只使用发送邀请的功能和模拟用户通过邀请注册的功能link?

feature "User sends invite" do
  scenario "to a valid email address" do
    # ...
    expect(page).to have_content "Your invite was sent to user@example.com"
  end
end

feature "Invitee signs up" do
  scenario "by accessing an invite link" do
    invite = Invite.create
    visit invite_path(invite)
    # ...
  end
end