6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

minitestでloggerの出力内容をテスト

Last updated at Posted at 2019-01-10

バッチ処理のテストを書いた時のメモみたいなものです。

バージョン

  • Rails 5.2.1
  • minitst 5.11.3

サンプル

以下のような、DBのデータを削除するバッチ処理があったとします。

class DeleteBatch

  # データ削除バッチ(適当)
  def run
    Rails.logger.info("#{self.class.name} run")

    begin
      ActiveRecord::Base.transaction do
        deleted_something_models = SomethingModel.where("deleted_at < ?", Time.current.ago(1.month)).destroy_all
      end
      Rails.logger.info("#{self.class.name} #{deleted_something_models.count} records deleted")
      Rails.logger.info("#{self.class.name} successed")
    rescue => e
      Rails.logger.error("#{self.class.name} failed")
    end
  end

end

ログの出力内容をテストします。

require 'test_helper'
require 'minitest/mock'

class DeleteBatchTest < ActiveSupport::TestCase

  test "ログの内容をテスト" do
    # 削除される想定のデータを投入(省略)

    # 期待するログの内容を定義
    expected_log = [
      "DeleteBatch run",
      "DeleteBatch 10 records deleted",
      "DeleteBatch successed",
    ]

    index = 0
    assert_arg_proc = -> (actual_log) do
      assert_equal(expected_log[index], actual_log)
      index += 1
      return
    end

    Rails.logger.stub(:info, assert_arg_proc) do
      # stubによって、このブロック内では Rails.logger.info は assert_arg_proc に置き換わる。
      # Rails.logger.info("abc")が呼ばれたら、assert_arg_proc("abc")が実行されるということ。

      delete_batch = DeleteBatch.new
      delete_batch.run
    end

    assert_equal(expected_log.size, index)
  end
end

サンプルのケースでは処理が単純なのでログを見る必要性はあまり無いですが、
色々する長いバッチ処理を書いてしまった時には使えるかと思います。

6
0
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
6
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?