Testing flash messages on redirect with RSpec

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)
else
flash.now[:error] = @location.errors.messages
render action: 'new'
end

# 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)
end

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

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

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.