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

Rspecでredirect_back()をテストする

Last updated at Posted at 2025-03-20

redirect_back()

  • Rails のコントローラで使用されるメソッドで、元のページにリダイレクトさせるために使われる。

  • redirect_back() を使った処理をテストするときは、request.env["HTTP_REFERER"] を設定して検証する。

バージョン

Rails:5.2.6
Ruby:2.7.4
RSpec:5.1.2

実装例

example_controller.rb
class ExampleController < ApplicationController
  def hoge
    # リファラが存在すればそのページにリダイレクト
    # 存在しなければ fallback_location で指定した URL('example/bar')にリダイレクト
    redirect_back(fallback_location: url_for(controller: 'example', action: 'bar'))
  end

  def foo
  end

  def bar
  end
end
example_controller_spec.rb
require 'rails_helper'

RSpec.describe ExampleController, type: :controller do
  # url_for() を使うため、 Rails のルーティングヘルパーを include する
  include Rails.application.routes.url_helpers

  # リダイレクト先の URL を指定
  #「only_path: true」はホスト部分を除いてパスのみを指定するオプション
  let(:redirect_url) { url_for(controller: 'example', action: 'foo', only_path: true) }
  let(:fallback_url) { url_for(controller: 'example', action: 'bar', only_path: true) }

  describe "#hoge" do
    context "リファラが設定されていない場合" do
      before do
        # request.env["HTTP_REFERER"] に nil を設定し、
        # リファラ(前ページのURL)が存在しない状態にする
        request.env["HTTP_REFERER"] = nil
      end

      it "元のページにリダイレクトする" do
        # ExampleController の hoge アクションを呼び出すリクエストを送る
        get :hoge
        # レスポンスが `fallback_url` にリダイレクトされることを確認
        expect(response).to redirect_to(fallback_url)
      end
    end

    context "リファラが設定されている場合" do
      before do
        # リファラを設定。
        request.env["HTTP_REFERER"] = redirect_url
      end

      it "redirect_url にリダイレクトすること" do
        # hoge アクションを呼び出すリクエストを送る
        get :hoge
        # レスポンスが redirect_url にリダイレクトされることを確認
        expect(response).to redirect_to(redirect_url)
      end
    end
  end
end

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?