TempingでMixinするmoduleのテストをしてみる٩( ‘ω’ )و

RailsでモデルにMixinするモジュールをテストしたいとき、みなさんどうしてますか?

mock_model? stub_model? 自分のダミーテーブル作る? 各モデルでテストする?

どれも意外と面倒くさい

そんなときはTempingを使うと楽ちん

ActiveSupport::Concernのモジュールをテストしてみましょう

# app/modules/logical_delete_scopes.rb
module LogicalDeleteScopes
  extend ActiveSupport::Concern
  included do
    scope :without_deleted, -> { where(deleted_at: nil) }
    scope :only_deleted,    -> { where.not(deleted_at: nil) }
  end
end

ダミーのモデルを作る

# spec/support/dummy_model.rb
Temping.create :dummy_model do
  include LogicalDeleteScopes
  with_columns do |t|
    t.datetime :deleted_at
  end
end

テストコードを書く

# spec/modules/logical_delete_scopes_spec.rb
require 'rails_helper'
RSpec.describe LogicalDeleteScopes do
  let!(:enable_data)  { DummyModel.create(deleted_at: nil) }
  let!(:deleted_data) { DummyModel.create(deleted_at: DateTime.now) }

  example do
    expect(DummyModel.without_deleted).to match_array [ enable_data ]
    expect(DummyModel.only_deleted).to match_array [ deleted_data ]
  end
end

Tempingはtemporary tableを使ってるので物理テーブルにも残らない github.com

Happy Hacking٩( ‘ω’ )و