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 Integration testing authentication

Spec Error: "undefined method `id' for nil:NilClass". The hacky workaround is not working for me.

The error refers to spec/controllers/users_controller_spec.rb as discussed in the first few minutes of this video.

it "sets the session user_id to the created user" do
  post :create, {:user => valid_attributes}, valid_session
  expect(session[:user_id]).to eq(User.find_by(email: valid_attributes["email"]).id)

$ bin/rspec --format=documentation spec/controllers/users_controller_spec.rb

  1) UsersController POST create with valid params sets the session user_id to the created user
     Failure/Error: expect(session[:user_id]).to eq(User.find_by(email: valid_attributes["email"]).id)
       undefined method `id' for nil:NilClass
     # ./spec/controllers/users_controller_spec.rb:103:in `block (4 levels) in <top (required)>'

I can only assume that for some reason it doesn't know that a User has an id.

I suspect I'm getting this error because earlier in the course I updated the rspec gem to get around another error. I've been able to work past all the other little problems this update has caused, but this one is beyond me. A google search indicated that stubbing might help get past it, but I really can't figure out how stubbing works.

Ruby v2.0
Rails v4.0.1
Full project code: git@bitbucket.org:GeoffreyEmerson/odot.git

Figured it out ten minutes after posting the question. Sheesh.

For some reason the gems that I'm using don't like to return hash values with the key in quotes.





and it started working fine.

1 Answer

Chris Ward
Chris Ward
12,129 Points

Glad to see you solved the problem. It's important to remember that the two naming forms aren't interchangeable, a variable starting with a colon can be stored differently than one with quotes. Coming from C++ and other languages to Ruby, this was one area that tripped me up. Hashes can help speed up searches and the value of adding them when you ordinarily wouldn't shouldn't be over looked. You could use a trapdoor function like md5 or sha256/512. Even a rudimentary partitioning attempt will suffice like combining the first four bytes of a file with its final four bytes. Well, good luck on your programming journey!