1

How can I check the content of a bounced email?

require "rails_helper"

RSpec.describe EventsMailbox do
  it "requires a current user" do
    expect(mail_processed).to have_bounced
    # here I would like to check the content of the bounced email
  end

  def mail
    Mail.new(
      from: "dorian@dorianmarie.fr",
      subject: "Some subject",
      body: "Some body"
    )
  end

  def mail_processed
    @mail_processed ||= process(mail)
  end
end
Dorian
  • 7,749
  • 4
  • 38
  • 57

1 Answers1

0

Here is how I did it, the key was that perform_enqueued_jobs that allows emails to be retrieved from ActionMailer::Base.deliveries:

require "rails_helper"

RSpec.describe EventsMailbox do
  include ActiveJob::TestHelper

  around(:each) { |example| perform_enqueued_jobs { example.run } }

  it "requires a current user", focus: true do
    expect(mail_processed).to have_bounced
    expect(last_delivery.from).to eq(["contact@socializus.app"])
    expect(last_delivery.to).to eq(["dorian@dorianmarie.fr"])
    expect(last_delivery_text).to(
      include("You need to be registered on Socializus")
    )
  end

  def mail
    Mail.new(
      from: "dorian@dorianmarie.fr",
      to: "party@events.socializus.app",
      subject: "Some subject",
      body: "Some body"
    )
  end

  def mail_processed
    @mail_processed ||= process(mail)
  end

  def last_delivery
    ActionMailer::Base.deliveries.last
  end

  def last_delivery_text
    return unless last_delivery
    text_part = last_delivery.parts.detect { _1.mime_type == "text/plain" }
    return unless text_part
    text_part.body.to_s
  end
end
Dorian
  • 7,749
  • 4
  • 38
  • 57
  • Using `def` inside an `RSpec.describe` is a little dangerous. Be careful not to override any methods of `RSpec::Core::ExampleGroup`. – Jared Beck Nov 16 '21 at 19:51
  • @JaredBeck isn't it the same as doing a `let`/`let!`? that could override a rspec method as well – Dorian Nov 17 '21 at 10:22
  • That's a good question. Maybe avoiding `def` is just a habit among myself and the people I've worked with. I've never dug deep to find out what happens if you define a `let` with the same name as an RSpec method. Also, [`def` does appear in the docs](https://relishapp.com/rspec/rspec-core/v/3-10/docs/helper-methods/arbitrary-helper-methods), which I never noticed before. – Jared Beck Nov 17 '21 at 18:23
  • yeah it uses `define_method` https://github.com/rspec/rspec-core/blob/fa1b5f5849ac0efe4ffab7d3d1a4e1cf87951541/lib/rspec/core/memoized_helpers.rb#L327 – Dorian Nov 17 '21 at 18:56