1
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?

【Rails】RSpec の ヘルパーの設定方法

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

RSpec でリクエストテストやモデルテストを書いていると、共通の処理(例:ログイン処理、JSON パース処理)を毎回書くのが面倒になることがあります。
そのような場合は、RSpec の ヘルパー(サポートファイル) を設定することで、テスト全体で使い回せるようになります。

本記事では Rails 8 + rspec-rails 8.0.1 を前提に、ヘルパー設定方法と注意点を解説します。


1. ヘルパーを作成する目的

  • ログイン処理の共通化
    Devise Token Auth などを使っている場合、access-tokenclientuid を毎回ヘッダーに渡すのは煩雑です。

  • 共通メソッドの利用
    JSON レスポンスのパースや API リクエストヘルパーを一括定義できます。


2. spec/support ディレクトリの作成

RSpec では、テスト用の補助コードは spec/support 以下に配置するのが一般的です。

mkdir spec/support

3. ヘルパーファイルを作成

例として、API 認証付きリクエストのヘルパーを作成します。

# spec/support/request_spec_helper.rb
module RequestSpecHelper

  # ログインして認証ヘッダーを取得
  def auth_headers_for(user)
    post api_v1_auth_sign_in_path, params: { email: user.email, password: user.password }
    response.headers.slice('access-token', 'client', 'uid')
  end

  # 認証付きGETリクエスト
  def get_with_auth(path, user, params: {})
    get path, params: params, headers: auth_headers_for(user)
  end

  # 認証付きPOSTリクエスト
  def post_with_auth(path, user, params: {})
    post path, params: params, headers: auth_headers_for(user)
  end
end

4. rails_helper.rb で読み込む

spec/support 以下のファイルを自動読み込みするために、rails_helper.rb のコメントアウトを外します。

# rails_helper.rb

# このコメントアウトを外さないと support ディレクトリ内のファイルが読み込まれない
Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }

注意
この行をコメントアウトしたままだと、spec/support に置いたヘルパーは読み込まれず、テストでエラーになります。


5. RSpec にヘルパーを include

読み込むだけでは使えないため、RSpec 設定に include します。

RSpec.configure do |config|
  config.include RequestSpecHelper, type: :request
end

これで request spec からヘルパーメソッドが利用可能になります。


6. 実際のテストで使う

RSpec.describe "Todos API", type: :request do
  let(:user) { create(:user) }

  it "認証付きでTodo一覧を取得できる" do
    get_with_auth api_v1_todos_path, user
    expect(response).to have_http_status(:ok)
  end
end

まとめ

  • **spec/support**以下にヘルパーを作成するのが一般的
  • **rails_helper.rb**の require 設定のコメントアウトを外すのを忘れない
  • config.include でテスト種別ごとにヘルパーを適用できる
1
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
1
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?