walktan’s blog

SIer勤務4年目。Web業界への転職計画遂行中。プログラミングなどの学習記録(備忘録)などを記していく。

RspecでControllerをテストする際、flashに値を渡す方法

RspecでControllerをテストする際、flashに値を渡す方法のメモ

<背景>
以下のような、flashの値で分岐処理しているactionをテストしたい

def my_action
  if flash[:something].nil?
    @hoge = flash[:something]
  end
end

<結論>
specにて、FlashHashクラスを使って渡す

before do
  flash_hash = ActionDispatch::Flash::FlashHash.new
  flash_hash[:something] = "hoge"
  session['flash'] = flash_hash.to_session_value
  get :my_action
end

it "@hogeがnilでないこと" do
  expect(assigns(:hoge)).not_to be_nil
end


ちなみに、↓これではmy_actionへ値が渡らなかった

before do
  flash[:something] = "hoge"
  get :my_action
end


(参考) stackoverflow.com

以上