Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby User Authentication with Rails Password Hashing and Sign In Testing Session Creation

Kevin Mulhern
Kevin Mulhern
20,374 Points

If statement for users controller breaks 2 tests

Hi, I am on the part where you have to make tests to make sure the 'new' template is rendered when the user enters blank credentials. Once I implement the if statement in the controller as shown in the video 2 of my other tests break.

here is the code for the controller:

def create
    user = User.find_by(email: params[:email])

    if user && user.authenticate(params[:password])
        session[:user_id] = user.id
        redirect_to todo_lists_path
    else
        render action: 'new'
    end
  end

These are the two tests that are breaking:

1) UserSessionsController POST 'create' with correct credentials redirects to the todo list path
     Failure/Error: expect(response).to be_redirect
       expected redirect? to return true, got false
     # ./spec/controllers/user_sessions_controller_spec.rb:25:in `block (4 levels) in <top (required)>'

  2) UserSessionsController POST 'create' with correct credentials sets the user_id in the session
     Failure/Error: expect(session[:user_id]).to eq(user.id)

       expected: 1
            got: nil

       (compared using ==)
     # ./spec/controllers/user_sessions_controller_spec.rb:42:in `block (4 levels) in <top (required)>'

1 Answer

Kevin Mulhern
Kevin Mulhern
20,374 Points

Problem was in the spec file, I had created a user with a password of "treehouse1" and was posting to authenticate with "teamtreehouse1". So the if statement was never returning true when authenticate was called.