LoginSignup
0
0

More than 1 year has passed since last update.

【RSpec】テスト用のヘルパーモジュールを定義し、テストの種類ごとに読み込む

Posted at

はじめに

タイトルの通り、テストの種類(request, model)毎にヘルパーを読み込む方法をまとめておく。

結論

spec/rails_helper.rbconfig.include ModelSpecHelper, type: :model などのようにtypeを指定して読み込むモジュールを定義する。

詳細

まず、spec/support/配下にテストで読み込みたいテストを含んだモジュールを用意する。

spec/support/model_spec_helper.rb

module ModelSpecHelper
  def 〇〇
    ~~~~~
  end
end

spec/rails_helper.rbに以下のように

RSpec.configure do |config|
  # ~~~~~~
  config.include JobSpecHelper, type: :job
  config.include ModelSpecHelper, type: :model
  config.include RequestSpecHelper, type: :request
  config.include AuthorizationHelper, type: :request
  # ~~~~~~
end

読み込みたいテスト毎にinclude~typeを記載する。

あとは、例えばテスト側で、

RSpec.describe "Api::V1::Auth::Registrations", type: :request do

とtypeを指定すれば上記のRequestSpecHelper, AuthorizationHelper が読み込まれ、その内部のメソッドが使えるようになる。

おわりに

簡単にメソッドをモジュールに切り出せるので、テストコード内で何度もメソッドを定義することがなくなり重複がなくなる。コードをDryに保つことは大切なので積極的にモジュール化していきたい。

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