Rails Tutorial 8.2: Log in Log out - ruby-on-rails

Working through the Rails Tutorial and in chapter 8 I can't get one of my tests to pass. Been checking around for hours... any help would be greatly appreciated.
ERROR["test_login_with_valid_information", UsersLoginTest, 2015-09-07 00:25:37 -0700]
test_login_with_valid_information#UsersLoginTest (1441610737.31s)
BCrypt::Errors::InvalidHash:
BCrypt::Errors::InvalidHash: invalid hash
app/controllers/sessions_controller.rb:8:in `create'
test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'
app/controllers/sessions_controller.rb:8:in `create'
test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'
22/22: [============] 100% Time: 00:00:00, Time: 00:00:00
Finished in 0.46288s
22 tests, 44 assertions, 0 failures, 1 errors, 0 skips
users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end

I know it's been a while since originally posted, but I had exactly the same error and my problem was a typo (missing =) in
users.yml
michael:
name: Michael Example
email: michael#example.com
password_digest: <% User.digest('password') %>
where it should have been
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>

#PraveenGeorge is correct - you need to back track and review your code at least since the last time the tests passed. Based on the fact that the content of the two files you've shared match to the tutorial, the problem lies elsewhere (and, unfortunately, out of sight from us on SO).
Perhaps it's in user.rb where you def User.digest(string) or in sessions_helper.rb?

Dear #Travislogan : As the ruby on rails tutorial itself is self explanatory in most possible way, you might have missed some of the steps/code before you reached into the section 8.2. So please cross check all tests and your project code from at least the previous chapter to the current one , one more time.It will help you to find out the error in your code.

Related

How does rails create a temp database from a yml file?

Following the rails tutorial https://www.railstutorial.org/book/basic_login.
users.yml
michael:
name: Michael Example
email: michael#example.comm
password_digest: <%= User.digest('password') %>
users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "login with valid information" do
get login_path
post login_path, params: { session: { email: #user.email,
password: 'password' } }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
end
Through debugging user Michael can log in without signing up because I suspect that users.yml became a database, but how did it do that?
Is there any way to figure this out through byebug or pry?
I suspect that users.yml became a database
Close, but not quite. Contents of users.yml were inserted in your test database (which is configured in database.yml).
This is called fixtures.

Hartl tutorial ch 8.2.4: Test errors when using fixtures

The login test
$ bundle exec rake test TEST=test/integration/users_login_test.rb \
> TESTOPTS="--name test_login_with_valid_information"
should pass, but I get the error message: "ActiveRecord::Fixture::FormatError:" 3 times. A number of other similar posts have been answered with the advice to check the .yml file as it needs to see spaces, not tabs. I tried pasting directly into the file from the tutorial, and have tried all sorts of combinations of tabs and spaces, but cannot get rid of this error. Here is my /test/fixtures/users.yml file:
#michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
Here is my /test/integration/users_login_test.rb file:
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
end
Any assistance would be greatly appreciated, things have been going so well, it's frustating to grind to a halt!
In your test/fixtures/users.yml file:
#michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
there is an unnecessary # (comments) in front of michael.
[reference: Rails Tutorial repo]

expecting x but rendering y

I have the following errors:
1) Failure:
UsersLoginTest#test_login_with_invalid_information [/REDACTED/users_login_test.rb:32]:
expecting <"session/new"> but rendering with <["sessions/new", "layouts/application"]>
2) Failure:
UsersEditTest#test_unsuccessful_edit [/REDACTED/test/integration/users_edit_test.rb:11]:
expecting <"users/edit"> but rendering with <[]>
3) Failure:
UsersEditTest#test_successful_edit [/REDACTED/test/integration/users_edit_test.rb:22]:
expecting <"users/edit"> but rendering with <[]>
Relevant code from user_login_test.rb:
test "login with invalid information" do
get login_path
assert_template 'session/new'
post login_path, session: { email: "", password: "" }
assert_template 'session/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
users_edit_test.rb:
require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
#user = User.find_by_name(:testuser)
end
test "unsuccessful edit" do
log_in_as(#user)
get edit_user_path(#user)
assert_template 'users/edit'
patch user_path(#user), user: { name: "",
email: "foo#invalid",
password: "foo",
password_confirmation: "bar" }
assert_template 'users/edit'
end
test "successful edit" do
log_in_as(#user)
get edit_user_path(#user)
assert_template 'users/edit'
name = "Foo Bar"
email = "foo#bar.com"
patch user_path(#user), user: { name: name,
email: email,
password: "",
password_confirmation: "" }
assert_not flash.empty?
assert_redirected_to #user
#user.reload
assert_equal name, #user.name
assert_equal email, #user.email
end
end
After several grueling hours of trying to hunt down the problem, I am still unable to find it. Tracing through the several problems, I feel like it might be a problem with the following test login code:
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
get login_path
post login_path, session: { email: user.name,
password: password,
remember_me: remember_me
}
else
session[:user_id] = user.id
end
end
I'm happy to update with more information as needed, but I'm pretty much at a loss.
It seems you redirected instead of rendering. Try that:
expect(response).to redirect_to root_path
to make sure you're redirected
I'm currently working through chapter 9 of the same Rails tutorial, and I ran into pretty much the same issue. After playing around in the console for a while I decided to just test it manually in the browser and was indeed unable to get to my edit page even though I was logged in. Which got me thinking that it might not be a problem with my tests but instead with the authorization in the users_controller.
Turns out I had completely forgotten to put the redirect_to login_url (in the logged_in_user filter) within an unless block so it was always just redirecting to the login page no matter what. The correct code is:
def logged_in_user
unless logged_in?
flash[:danger] = 'Please log in.'
redirect_to login_url
end
end
Now my tests are passing. Perhaps you've run into a similar issue. Either way I've often found it useful to just return to the browser and try to replicate the integration tests manually, just to figure out if it's a problem with my code or I've just written a dodgy test.

Experiencing errors in The Rails Tutorial Chapter 8

I tried fixing it but to no avail. I'm pretty sure I followed the tutorial. This happened in chapter 8 of The Rails Tutorial.
Here is the error when i run bundle exec rake test
ERROR["test_current_user_returns_nil_when_remember_digest_is_wrong", SessionsHelperTest, 2015-09-17 16:33:02 +0100]
test_current_user_returns_nil_when_remember_digest_is_wrong#SessionsHelperTest (1442503982.53s)
NoMethodError: NoMethodError: undefined method `user' for #<SessionsHelperTest:0xbdef3ba8>
test/helpers/sessions_helper_test.rb:6:in `setup'
test/helpers/sessions_helper_test.rb:6:in `setup'
ERROR["test_current_user_returns_right_user_when_session_is_nil", SessionsHelperTest, 2015-09-17 16:33:02 +0100]
test_current_user_returns_right_user_when_session_is_nil#SessionsHelperTest (1442503982.55s)
NoMethodError: NoMethodError: undefined method `user' for #<SessionsHelperTest:0xb9575274>
test/helpers/sessions_helper_test.rb:6:in `setup'
test/helpers/sessions_helper_test.rb:6:in `setup'
ERROR["test_login_with_remembering", UsersLoginTest, 2015-09-17 16:33:02 +0100]
test_login_with_remembering#UsersLoginTest (1442503982.61s)
NoMethodError: NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:51:in `block in <class:UsersLoginTest>'
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:51:in `block in <class:UsersLoginTest>'
ERROR["test_login_without_remembering", UsersLoginTest, 2015-09-17 16:33:02 +0100]
test_login_without_remembering#UsersLoginTest (1442503982.73s)
NoMethodError: NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:56:in `block in <class:UsersLoginTest>'
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:56:in `block in <class:UsersLoginTest>'
28/28: [=======================================================================================================] 100% Time: 00:00:03, Time: 00:00:03
Finished in 3.29948s
28 tests, 62 assertions, 0 failures, 4 errors, 0 skips
test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Logs in a test user.
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
post login_path, session: { email: user.email,
password: password,
remember_me: remember_me }
else
session[:user_id] = user.user_id # this is line 27
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_reditect)
end
end
test/helpers/sessions_helper.rb
require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
def setup
#user = user(:microte) # Line 6
remember(#user)
end
test "current_user returns right user when session is nil" do
assert_equal #user, current_user
assert is_logged_in?
end
test "current_user returns nil when remember digest is wrong" do
#user.update_attribute(:remember_digest, User.digest(User.new_token))
assert_nil current_user
end
end
test/integration/users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:microte)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
test "login with valid information follwed by logout" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert is_logged_in?
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
# Simulate a user clicking logout in a second window
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(#user), count: 0
end
test "login with remembering" do
log_in_as(#user, remember_me: '1') # Line 51
assert_not_nil cookies['remember_token']
end
test "login without remembering" do
log_in_as(#user, remember_me: '0') # Line 56
assert_nil cookies['remember_token']
end
end
Thanks for your help.
It looks like the first two errors are in your session_helper: your setup defines #user = user(:microte).
Not sure about the errors in the remembering tests are; the tests you've shared appear to be fine. I suggest you compare the code changes against what's in the tutorial to see what the cause of these errors are.
Seems like you are getting an error when trying to pull out a user from your fixtures. Check your fixtures/users.yml file and see if you have a microte user defined. It should look something like this(just an example):
microte:
name: "Test User"
email: "test_user#example.com"
password_digest: <%= User.digest("password")%>
slug: <%= "Test User".parameterize %>
activated: true
In the tutorial the user provided is named :michael
As others before me have noted, you wrote :microte instead.
Check in your users.yml fixture how you named him there, and make sure they match.
As a bit of explanation: in the beginning of your test there is a setup method that prepares your test setting:
def setup
#user = users(:microte)
end
the user you are instantiating here, is put into the fixtures file.

Test doesn't pass in 8.20 railstutorial

FAIL["test_test_login_with_valid_information", UsersLoginTest, 2015-08-27 20:00:02 +0000]
test_test_login_with_valid_information#UsersLoginTest (1440705602.54s)
Expected at least 1 element matching "a[href="/users.762146111"]", found 0..
Expected 0 to be >= 1.
test/integration/users_login_test.rb:18:in `block in '
2/2:
[=======================================================================================================] 100% Time: 00:00:00, Time: 00:00:00
Finished in 0.46825s 2 tests, 10 assertions, 1 failures, 0 errors, 0
skips
Here's user_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "test login with valid information" do
get login_path
post login_path, session: {email: #user.email, password: "password"}
assert_redirected_to #user
follow_redirect!
assert_template "users/show"
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", users_path(#user)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert flash.any?
get root_path
assert flash.empty?
end
end
User.yml
michael:
name: michael
email: michael#example.com
password_digest: <%= User.digest("password") %>
I'd double-check your header template and confirm that the appropriate code is there for the "Profile" link (listing 8.16) as that appears what's failing the test.
I'm not super savvy with Rails, but this part of the error has me a little concerned: matching "a[href="/users.762146111"]". I'd expect that to be /users/762….

Resources