LoginSignup
1
1

More than 1 year has passed since last update.

【rails】【rspec】RspecでRails のActionMailer の本文をテストする

Posted at

はじめに

未経験からエンジニアに転職して、4ヶ月ほど経つエンジニアです。
RspecでRails のActionMailer のメール本文に期待通りの文章が表示されているかどうか
をテストする方法についてです。

アイコンバー.JPG

結論

expect(ActionMailer::Base.deliveries.last.html_part.body.to_s).to match("メール本文の内容を書きます")

上記のように↓を使うとテストできます。

expext(XXXX.html_part.body.to_s).to match("")

具体例

# models/send_mail.rb
def send_mail
  # メールを送信する処理
  mail.deliver_now
end

# spec/models/send_mail.rb
 it 'メール本文が適切であること' do
   expect { Model.send_mail }.to change(ActionMailer::Base.deliveries, :count).by(5)
   expect(ActionMailer::Base.deliveries[0].html_part.body.to_s).to match("期待通りのメール本文が表示される")
 end

補足

expext(XXXX.text_part.body.to_s).to match("")

↑だとテキスト形式でメールが描画され、その形式でテストすることも可能です。

また、以下のようにすることでメールの送信元、送信先なども検証できます。

expect(mail.from.first).to eq('fuga.mail@test.com')
expect(mail.to.first).to eq('hoge.mail@test.com')
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1