Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.