【问题标题】:Test if html contains image tag with .png file Ruby测试html是否包含带有.png文件Ruby的图像标签
【发布时间】:2018-07-05 19:25:11
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails ruby-test


    【解决方案1】:

    这是来自典型 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
    

    【讨论】:

    • 感谢您的回答。这与我正在寻找的相似!
    【解决方案2】:

    我不确定它是否有效,但我想你可以这样做。

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

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

    【讨论】:

    • 我不得不使用assert_match,但@Phlip 的回答更符合我的要求。感谢您的建议!
    猜你喜欢
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2011-05-07
    • 2012-07-08
    • 2011-02-03
    • 2012-10-22
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多