Testing email delivery with Capybara in a Rails app using Mailgun

Hey everyone! I’m working on a Rails app and I’m trying to figure out how to test my email functionality using Capybara. I’m using Mailgun for sending emails, but I’m struggling with the testing part.

Here’s a simplified version of how I’m sending emails:

def send_notification
  Mailgun::Client.new(ENV['MAILGUN_API_KEY']).send_message(
    ENV['MAILGUN_DOMAIN'],
    {
      from: '[email protected]',
      to: user.email,
      subject: 'Important Update',
      text: 'Check out the latest changes in your account!'
    }
  )
end

The emails are sending fine, but I can’t seem to get Capybara to work with them for testing. I tried capybara-email, but it didn’t help. Does anyone have experience with this or know a good way to test email delivery in acceptance tests?

Also, if I manage to get the email content in my tests, how can I test clicking on links within the email? Any tips or examples would be super helpful. Thanks in advance!

hey, i’ve dealt with this before. try using the ‘mail_catcher’ gem. it’s pretty neat for catching emails in development. just set it up in your test environment and you can easily grab the sent emails.

For testing links, you could parse the email content and extract URLs. then use capybara to visit those links. it’s not perfect, but it works ok for most cases.

I’ve faced similar challenges when testing email functionality in Rails apps. One approach that worked well for me was using the ‘letter_opener’ gem in combination with ‘webmock’ for stubbing API calls to Mailgun.\n\nFirst, configure your test environment to use ‘letter_opener’ instead of actually sending emails. This captures emails locally. Then, use ‘webmock’ to intercept and stub the Mailgun API calls.\n\nFor testing email content and clicking links, you can access the rendered emails through Letter Opener’s API. Here’s a basic example:\n\nruby\nrequire 'letter_opener'\nrequire 'webmock'\n\n# In your test\nstub_request(:post, /api.mailgun.net/).to_return(status: 200)\nsend_notification\nemail = ActionMailer::Base.deliveries.last\nexpect(email.subject).to eq('Important Update')\n\n# To test clicking links\nhtml_body = email.html_part.body.to_s\ndoc = Nokogiri::HTML(html_body)\nlink = doc.at_css('a')['href']\nvisit link\n\n\nThis approach has worked reliably for me in several projects. Hope it helps!