LoginSignup
5
6

More than 5 years have passed since last update.

[Rails] redirect時のflashとrender時のflashの違い

Posted at

redirect時のflashとrender時のflashの違い

これがscaffoldした時のupdateコードですね(手元のコードから持ってきたのでやや違うかもしれませんが)

update成功時はredirectですが、update失敗時はrenderしています。

items_controller.rb
def update
  respond_to do |format|
    if @item.update(clan_params)
      format.html { redirect_to @item, notice: 'Item was successfully updated.' }
      format.json { render :show, status: :ok, location: @item }
    else
      format.html { render :edit }
      format.json { render json: @item.errors, status: :unprocessable_entity }
    end
  end
end

redirect時のflash

flashです。
flash[:success]やflash[:notice]、flash[:error]を使って中身のテストができる。

render時のflash

flash.nowです。
中身のテストは出来ない(描画時は存在するがテスト時にはすでに破棄されているため)
必死にflash内容をテストしようとしても無理です。
テストも壊れやすくなるし、表示あり/なしくらいをテスト対象にしましょう。

参考にしたサイト

拝啓、シーシュポス: [Rails] flash.now[:notice]とflash[:notice]の違い

ザリガニが見ていた...。: flash.nowの内容を直接テストすることは不可能

5
6
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
5
6