0
0

リダイレクト先をテストする

Last updated at Posted at 2024-07-18
require "rails_helper"

RSpec.describe UsersController,type: :controller do
  describe "create user transition page" do
    it "assigns @user" do
      post :create, :params => {:name => "hogehoge", :email => "gehogeho"}
      expect(response).to redirect_to(:action => 'show',id: assigns(:user).id)
    end

    it "not assigns @user" do
      post :create, :params => {:name => "", :email => ""}
      expect(response).to redirect_to(:action => 'new')
    end
  end
end

render_templateからredirect_toに変更したらテストが通った。
インスタンス変数を保存した後リダイレクトしていたため変更した。

The render_template matcher is used to specify that a request renders a given template or layout. It delegates to assert_template
It is available in controller specs (spec/controllers) and request specs (spec/requests).
NOTE: use redirect_to(:action => 'new') for redirects, not render_template.

出典

https://rspec.info/features/6-0/rspec-rails/matchers/render-template-matcher/#:~:text=The%20render_template%20matcher,not%20render_template.

assigns(key = nil) アクションを実行した結果、インスタンス変数に代入されたオブジェクトを取得

出典

感想

とりあえずコントローラのテストを簡単にできてよかった。
またテストのタイトル、場合わけの英文には問題あり。

asssigns(:user)とするとコントローラの@userにすることができることを知れてよかった。

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