Testing flash messages on redirect with RSpec

Dana Hartweg
Feb 22, 2014 · 1 min read

For some reason, using RSpec to test a flash message displayed during a redirect is a huge problem. After much searching, I found a method that works well for me. Hope it saves someone some time down the road!

The code

# app/controllers/locations_controller.rb

if @location.save
flash[:success] = 'Location was successfully created.'
redirect_to location_path(@location)
flash.now[:error] = @location.errors.messages
render action: 'new'

# spec/controllers/locations_controller_spec.rb

describe "POST #create" do
context "valid attributes" do
subject { post :create, location: attributes_for(:location) }

it "creates a new location" do
expect{ subject }.to change(Location, :count).by(1)

it "redirects to the location on save" do
expect( subject ).to redirect_to :action => :show, :id => assigns(:location).id

it "flashes a success message" do
expect( subject.request.flash[:success] ).to_not be_nil

For whatever reason, it’s necessary to access the flash hash via the request object instead of the response. No doubt redirection is the culprit here.

Originally published at danahartweg.com on February 22, 2014.

    Dana Hartweg

    Written by

    Senior Front End Software Engineer, InVision Studio

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade