测试 html 是否包含带 .png 文件的图像标签 Ruby

Test if html contains image tag with .png file Ruby

我在 Rails 网络应用程序上的 Ruby 向客户发送了一封欢迎电子邮件,我想编写一个测试以确保该电子邮件包含一个标签,其中 src 是一个 .png 文件。我看到 assert_select 可能会做我想做的事,但由于我的电子邮件是 Mail::Message class,我只能从电子邮件中获取 html。在此先感谢您的帮助!

我不确定它是否有效,但我想你可以做类似的事情。

expect(mail.body).to match(/.*.<img.*.png.*/)

https://github.com/rspec/rspec-expectations#regular-expressions

这里是来自示例 Redmine 的 assert_select_email

assert_select_email do
  assert_select 'a[href^=?]', 'http://localhost:3000/settings'
end

所有 Rails 程序员都应该学习像 Redmine 这样的文献来学习很多有用的技巧。

    # Extracts the body of an email and runs nested assertions on it.
    #
    # You must enable deliveries for this assertion to work, use:
    #   ActionMailer::Base.perform_deliveries = true
    #
    #  assert_select_email do
    #    assert_select "h1", "Email alert"
    #  end
    #
    #  assert_select_email do
    #    items = assert_select "ol>li"
    #    items.each do
    #       # Work with items here...
    #    end
    #  end
    def assert_select_email(&block)
      deliveries = ActionMailer::Base.deliveries
      assert !deliveries.empty?, "No e-mail in delivery list"

      deliveries.each do |delivery|
        (delivery.parts.empty? ? [delivery] : delivery.parts).each do |part|
          if part["Content-Type"].to_s =~ /^text\/html\W/
            root = Nokogiri::HTML::DocumentFragment.parse(part.body.to_s)
            assert_select root, ":root", &block
          end
        end
      end
    end