郵件測試


使用 ActionMailer 中可以看到:

~$ rails generate mailer UserMailer
      create  app/mailers/user_mailer.rb
      invoke  erb
      create    app/views/user_mailer
      invoke  test_unit
      create    test/functional/user_mailer_test.rb

可看到除了產生郵件模型之外,還產生了郵件功能測試檔案:

  • user_mailer_test.rb
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
  # test "the truth" do
  #   assert true
  # end
end

郵件測試案例是繼承自ActionMailer::TestCase。在測試環境中設定檔test.rb中,config.action_mailer.delivery_method是設定為:test,這個設定下郵件並不會真的發送出去,而會儲存至ActionMailer::Base.deliveries陣列中。

以測試 使用 ActionMailer 中的例子來說,在純文件與HTML樣版都存在的情況下,可如下測試郵件:

  • user_mailer_test.rb
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
    test "welcome mail" do
        user = Class.new {
            def email
               "some@gmail.com"
            end
            def name
               "Some"
            end
        }.new

        email = UserMailer.welcome(user).deliver

        assert !ActionMailer::Base.deliveries.empty?
        assert_equal [user.email], email.to
        assert_equal "Welcome to Openhome.cc", email.subject
        assert_match /Welcome to Openhome.cc, #{user.name}/, email.encoded
assert_match /<h1>Welcome to Openhome.cc, #{user.name}<\/h1>/, email.encoded
  end end

也可搭配fixtures與@expected來測試,例如若想測試純文字郵件,可在test/fixtures/user_mailer資料夾中準備welcome檔案如下:
  • welcome
Welcome to Openhome.cc, Some
Thanks for joining and have a great day!

然後如下撰寫測試:

  • user_mailer_test.rb
require 'test_helper'

class UserMailerTest < ActionMailer::TestCase
    tests UserMailer
    test "welcome mail" do
        @expected.from    = 'example@gmail.com'
        @expected.to      = 'some@gmail.com'
        @expected.subject = "Welcome to Openhome.cc"
        @expected.body    = read_fixture("welcome") # 讀取test/fixtures/user_mailer/welcome 檔案

        user = Class.new {
            def email
               "some@gmail.com"
            end
            def name
               "Some"
            end
        }.new

        assert_equal @expected, UserMailer.welcome(user)
    end
end