DrFunk
DrFunk

Reputation: 33

How to check the final rendered view in Rspec after redirect_to?

I'm running Rails tests with Rspec and for actions that redirect, it is checking the redirect page, not the final destination page. It makes sense, but it isn't what I want. I want to make sure that a flash message is rendered. Is it impossible to properly test the final view in a redirected destination with have_selector? For example, a simple create action:

class UsersController < ApplicationController

def show
  @user = User.find(params[:id])
  @page_title = @user.name
end

def create
  @user = User.new(params[:user])
  if @user.save
    flash[:success] = "You have successfully signed up!"
    redirect_to @user
  else
    flash[:error] = "There were errors signing up."
    @page_title = "Sign Up"
    render 'new'
  end
end

fails under this test:

it "should have flash message to notify user that signup was successful" do
    post :create, :user => @attr
    response.should have_selector("div.flash-success")
end   

with this error:

Failure/Error: response.should have_selector("div.flash-success")
   expected following output to contain a <div.flash-success/> tag:
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
   <html><body>You are being <a href="http://test.host/users/1">redirected</a>.</body></html>

Environment:

Upvotes: 0

Views: 953

Answers (2)

Nebojsa
Nebojsa

Reputation: 169

This is the way to test flash messages:

it "should have flash message to notify user that signup was successful" do
    post :create, :user => @attr
    flash[:success].should eql "You have successfully signed up!"
end

Upvotes: 2

nmott
nmott

Reputation: 9604

Have you considered using shoulda-matchers for testing Controllers with rspec. They allow you to use the following to easily test flash messages.

it { should set_the_flash.to(/created successfully/i) }

You don't have to query a selector on a page. As a bonus you get a set of other matcher for testing routes, redirects, renders, layout and HTTP responses. I found it easier to track down issues when I was using them.

See shoulda-matchers if it sounds like it might help.

Upvotes: -1

Related Questions