LoginSignup
1
0

More than 3 years have passed since last update.

Rspecテストでredirect_backの挙動をテストする

Last updated at Posted at 2021-05-23

Rspecテストでredirect_back(fallback_location: root_path)のコードのRspecでのテスト方法で躓いてしまったので、解決法をシェアしたいと思います。

前提条件としてUserとWalkcourseが1対多の関係を持っている状態となっており、Walkcourse Controllerのdestoryアクションで、walkcourseを削除した場合、リファラー(直前のページ)にリダイレクトするという挙動になるよう規定しています。

def destroy
   @walkcourse = Walkcourse.find(params[:id])
   @walkcourse.destroy
   flash[:success] = 'メッセージを削除しました。'
   redirect_back(fallback_location: root_path)
end

以下にはRspecテストの該当部分に関して記述しています。
loginuserがwalkcourseを削除した場合の挙動に関するテストで、before以下にリファラーについての情報を書き、redirect_to以下に指定していたリファラーについての情報を書けばそのままテストは成功しました。

describe '#destroy' do
    context 'loginuserの場合' do
      before :each do
        sign_in user
        request.env["HTTP_REFERER"] = "where_i_came_from"
      end
      it '正常に削除できること' do
        expect{walkcourse.destroy}.to change(Walkcourse, :count).by(-1)
      end
      it '削除した後、リファラーページもしくはルートページにリダイレクトすること' do
        delete :destroy, params: {id: walkcourse.id}
        expect(response).to redirect_to "where_i_came_from"
      end
    end
end

参考ページ:https://stackoverflow.com/questions/6040479/rspec-testing-redirect-to-back/6729817#6729817
https://myzk.dev/rspec-referee/

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