Search code examples
ruby-on-railscapybara

Capybara-email save and open specific email in ActionMailer::Base.deliveries


I have an old project I'm updating soon, which currently uses Capybara ~> 3.6 and Capybara-email.

There's two emails that coincidentally fire off to the same email in a particular test, and I would like to look at both, but open_email('[email protected]') only opens the last email when current_email.save_and_open

Any way to set ActionMailer::Base.deliveries[2] in open_email, or otherwise somehow look at both?


Solution

  • Based on the Source Code open_email, which is an alias for first_email_sent_to (a very misleading name), just pulls the last email sent to a given email address and assigns it to current_email:

    def first_email_sent_to(recipient)
      self.current_email = emails_sent_to(recipient).last
    end
    alias :open_email :first_email_sent_to
    

    This method utilizes emails_sent_to so we can leverage that method to get the last 2 emails sent to that address.

    emails_sent_to('[email protected]').last(2) 
    

    Since save_and_open just opens a browser to view the email we should be able to achieve your desired functionality using:

    emails_sent_to('[email protected]').last(2).each(&:save_and_open)
    

    Since emails_sent_to is simply an Array of Capybara::Node::Email objects, if you need to target something other than the last 2 you can filter them in any way you see fit:

    target_emails = emails_sent_to('[email protected]').select do |email|
      # filter your emails here
      email.subject =~ /target description/i
    end