Rails教程第8章:is_logged_in如何?通过?

时间:2014-11-10 12:59:38

标签: ruby-on-rails ruby-on-rails-4 railstutorial.org

好的,所以我完成了章节,所有代码都运行正常。但我有点困惑。在sessions_helper_test中,我直接设置了记忆令牌cookie。针对is_logged_in的测试?传递,即使is_logged_in?仅检查会话。

require 'test_helper'

class SessionsHelperTest < ActionView::TestCase

  def setup
    @user = users(:michael)
    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

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
  include ApplicationHelper

  # Add more helper methods to be used by all tests here...

  def is_logged_in?
    !session[:user_id].nil?
  end
  ...
end


module SessionsHelper

  def log_in(user)
    session[:user_id] = user.id
  end

  # Remember user in persistent session
  def remember(user)
    user.remember  
    cookies.permanent.signed[:user_id] = user.id
    cookies.permanent[:remember_token] = user.remember_token
  end
  ...
end

class User < ActiveRecord::Base
  ...
  def remember
    self.remember_token = User.new_token
    update_attribute(:remember_digest, User.digest(remember_token))
  end
  ...
end

任何人都可以解释一下吗?

1 个答案:

答案 0 :(得分:3)

从我理解的代码'remember(@user)'创建cookie,'current_user'方法使用cookie在session为null时返回用户。

assert_equal @user, current_user

从书中,这里是current_user的代码:

module SessionsHelper
  .
  .
  .
  # Returns the user corresponding to the remember token cookie.
  def current_user
    if (user_id = session[:user_id])
      @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end
  .
  .
  .
end

从上面的代码中我猜,当用户使用remember_token cookies传递身份验证时,会调用“log_in”方法设置“session [:user_id]”