Matthias
Matthias

Reputation: 1953

Test failure: Expected response to be a <redirect>, but was <200>

I'm a newbie to rails and starting with setting up my first testing suite.

In my tests I keep getting the following failure:

Expected response to be a <redirect>, but was <200>

This response is odd, as the redirect clearly works when testing using the browser. Does anyone have an idea what could be going on here, or what is the best approach in diagnosing such problem. For example, is there a way to find out on what page the 200 message was given.

The test script (user_controller_test.rb)

test "when correct should redirect to dashboard" do
    log_in_as(@user_one)
    assert_redirected_to dashboard_url
end 

The full console message

 FAIL["test_should_get_dashboard_when_correct_user", UsersControllerTest, 2015-12-23 18:06:20 +1100]
 test_should_get_dashboard_when_correct_user#UsersControllerTest (1450854380.57s)
Expected response to be a <redirect>, but was <200>
test/controllers/users_controller_test.rb:27:in `block in <class:UsersControllerTest>'

The controller:

class SessionsController < ApplicationController

def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])

          log_in user         
          params[:session][:remember_me] == '1' ? remember(user) : forget(user)
          redirect_back_or dashboard
     else
      flash.now[:danger] = 'Invalid email/password combination'
      render 'new' 
    end
  end

Upvotes: 0

Views: 1442

Answers (1)

Mike S
Mike S

Reputation: 11409

You have a faulty test.

This is what the code in your controller says:

if user && user.authenticate(params[:session][:password])
  redirect_back_or dashboard
else
  render 'new' 
end

# if user is not nil AND user can authenticate with given params
  # success (redirect)
# else the params passed to the controller did not authenticate the user
  # fail (render 200)

Then your test says:

log_in_as(@user_one)
assert_redirected_to dashboard_url

# login user manually, rather than assign params
# check if the controller action redirected, meaning check if it could authenticate with the given params that you did not assign

See the problem? You need to set the params that the controller action is checking if you want it to pass the if statement.

Upvotes: 2

Related Questions