2
1

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.

Rails minitestでconcernsのテストを書く

Last updated at Posted at 2019-07-30

はじめに

concernsで実装はすっきりしたんだけど、minitestでテストを書くときにどうするんだっけ?と困った。rspecに入れ替えてshared_examples使おうという声が聞こえるけどたぶん錯覚なんだ。

実装サンプル

こんな感じのサンプルがありまして...

class SampleModel < ActiveRecord::Base
  include SampleConcern

  # name attribute defined
end
module SampleConcern
  extend ActiveSupport::Concern

  included do
    # concernsに実装するのはたぶん不適切だけど
    validate name, presence: true
  end

  def greet
    "I'm #{name}"
  end
end

テスト

SampleConcernActiveRecordに依存しない(has_manyとかvalidatesが書いていない)場合はただのmoduleなので、テスト用クラスを作ってincludeしてやれば済む。
大人の事情により、依存しているクラスをテストする場合は以下のコードでテストが書ける。
(module側のsetupincludedの中に定義することでテストクラスのsuper呼び出しを省略できるがケースバイケース)

require 'test_helper'
require 'models/sample_concern_test'

class SampleModelTest < ActiveSupport::TestCase
  include SampleConcernTest

  def setup
    super
  end

  private

  def test_instance
    SampleModel.new
  end
end
module SampleConcernTest
  extend ActiveSupport::Concern

  def setup
    @my_sample = test_instance
  end

  included do
    test "correct name greeting" do
      name = "paty"
      @my_sample.name = name

      assert_equal "I'm #{name}", @my_sample.greet
    end
  end

  private

  def test_instance
    raise NotImplementedError.new("override with InheritanceClass.new")
  end
end
2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?