upinetree's memo

Web系技術の話題や日常について。

Minitest の Unit style で DSL 風な around ヘルパーを定義する

RailsActiveSupport::TestCase を使っているとして、サクッとミニマムにやりたい。

minitest-around を使うと、以下のような around メソッドを定義することで setup/teardown をセットで実行できる。

require "test_helper"
require 'minitest/around/unit'

class CatTest < ActiveSupport::TestCase
  def around(&block)
    p "konnichi nyan"
    block.call
    p "sayouna nyan"
  end

  def test_nyan
    # ...
  end
end

でも、なんとなく ActiveSupport::TestCase が用意している setup, teardown と揃えてDSL風に使いたい。

require "test_helper"
require 'minitest/around/unit'

class CatTest < ActiveSupport::TestCase
  # こうしたい!
  around do |test|
    p "konnichi nyan"
    test.call
    p "sayouna nyan"
  end

  # これと同じ感じ
  setup do
    @cat = Cat.new
  end
end

なので test_helper.rb でこうする。

class ActiveSupport::TestCase
  def self.around(&block)
    define_method(:around) do |&test|
      instance_exec(test, &block)
    end
  end
end

Unit style でどこまで複雑なテスト設計に対応できるかは置いておいて、ちょっとした便利ネタでした。