How do I test for a redirect with RSpec?

I’m following the new version of Rails Tutorial. Chapter 9, exercise
5http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users?version=3.2#sec:updating_deleting_exercisesasks
to ensure that registered users can not access the new and create
methods in the users controller:

Signed-in users have no reason to access the new and create actions in
the
Users controller. Arrange for such users to be redirected to the root
url
if they do try to hit those pages.

To do this, I added a before filter to the users_controller.rb to check
if
a user is signed in on new and create:

before_filter :registered_user, only: [:new, :create]
def registered_user
  redirect_to user_path(current_user) if signed_in?
end

The before filter uses the same method (signed_in?) that my
authentication
system uses to check if the user is signed. In browser testing,
the behavior works as expected. I can’t, however, get RSpec to play
nice:
The second test that checks for a redirect fails:

  describe "visiting the sign up page" do
    before { visit sign_up_path }
    it { should_not have_selector('h1', text: 'Sign Up') }
    it { should_not have_selector('title', text: full_title('Sign 

Up’))
}
end

# This fails
  •  describe "submitting to the create action" do*
    
  •    before { post users_path(user) }*
    
  •    specify { response.should redirect_to(user_path(user)) }*
    
  •  end*
    

Giving me the following message:

  1. AuthenticationPages signin with valid information submitting to the
    create action
    Failure/Error: specify { response.should
    redirect_to(user_path(user)) }
    Expected response to be a <:redirect>, but was <200>

    ./spec/requests/authentication_pages_spec.rb:50:in `block (5

levels)
in <top (required)>’

Any idea why this is happening?

Two tips:

  1. You can tail the test log (tail -f log/test/log). This will show you
    which controller & action is actually being hit by your test – it is
    likely that this action isn’t getting hit.

  2. Try the debugger! Put “debugger” right after def registered_user,
    then make sure ‘ruby-debug’ or ‘ruby-debug19’ is in your Gemfile (hint:
    put it into a :test and :development group so that it doesn’t deploy to
    production), and when you run spec be sure to use the -d flag. If you
    can get it to drop into debugger on that line of code you know your app
    is getting to that action.

I don’t suppose the if signed_in? is the problem? I don’t see any place
in your test where you are logging in the user.

Good luck!

Jason

Jason, thank you very much. It turned out the test was not signing in
the
user correctly. Nevertheless, your suggestions are new information to me
and they have already proven themselves useful. Many thanks.

One thing that bothers me is the quantity of describe/end blocks, and
having to figure out where to insert new blocks… I guess that will
come
with experience.