動かざることバグの如し

近づきたいよ 君の理想に

RailsのActionMailerで差出人のメールアドレスを取得したい

環境

やりたいこと

ActionMailerを使ったメール送信周りのテストをしていて、

# メール1通送れているか
expect(ActionMailer::Base.deliveries.size).to eq(1)
mail = ActionMailer::Base.deliveries.last

expect(mail.subject).to eq("たいとる")
expect(mail.to).to eq(['aaaaaaaaaaa@example.com'])
expect(mail.body.encoded).to include("ほげほげ")
expect(mail.from).to eq(["aaaaa@example.com"])

といった形でメールに対してテストができる。mail.fromで差出人のメールアドレスが取得できるのだが、

はてなブログサポート事務局 <hatena@example.com>

のように名前を含むメールアドレスになってしまうと何故かうまく取れなくなる。(でテストにコケる

解決方法

mail[:from].value

で名前ごと取れる。つまり

mail = ActionMailer::Base.deliveries.last
expect(mail[:from].value).to eq('はてなブログサポート事務局 <hatena@example.com>')

みたいに可能。ベストなやり方かはわからんが

ちなみにこのやり方で取れるのは5以降らしい

参考リンク