Ccyan
Ccyan

Reputation: 1057

Test if html contains image tag with .png file Ruby

My Ruby on Rails web application sends a welcome email to clients and I want to write a test to make sure the email contains an tag where the src is a .png file. I saw assert_select might do what I want but since my email is a Mail::Message class, I can only grab the html from the email. Thanks in advance for the help!

Upvotes: 0

Views: 245

Answers (2)

Phlip
Phlip

Reputation: 5343

Here's assert_select_email from the exemplary Redmine:

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

All Rails programmers should study literature like Redmine to learn lots of helpful tricks.

    # 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

Upvotes: 3

htunc
htunc

Reputation: 475

I'm not sure if it works but i guess you can do something like that.

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

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

Upvotes: 1

Related Questions