私はMichael HartlのRails tutorial(これは信じられないほど素晴らしい方法です)を使って作業しています。チュートリアルの作業中にCookieに関連するrspecテストの問題
とにかく、すべてがうまくいっていて、10章の終わりに近づいています。問題は、私のrspecテストでいくつかの失敗が発生し始めて、何が間違っているのか理解できないことです。
最初の障害は、the section on destroying usersで処理していたときに発生しました。テスト
before :each do
@user = Factory :user
end
describe "as a non-signed-in user" do
it "should deny access" do
delete :destroy, :id => @user
response.should redirect_to(signin_path)
end
end
はエラーを与える:
UsersController DELETE 'destroy' as a non-signed-in user should deny access
Failure/Error: delete :destroy, :id => @user
NoMethodError:
undefined method `admin?' for nil:NilClass
# ./app/controllers/users_controller.rb:76:in `admin_user'
# ./spec/controllers/users_controller_spec.rb:308:in `block (4 levels) in <top (required)>'
はここusers_controllerのコードのメッセージの参照です:
def admin_user
# the error tels me that current_user = NilClass
redirect_to(root_path) unless current_user.admin?
end
だから私は、これはCURRENT_USERが正しく動作していないことを示唆していると思いますし、がnilに設定されています。現在current_userにはSessionsHelperの多くのメソッドが含まれています。これは、安全なCookieでユーザーIDを設定し、Cookieがサイトを移動する際に参照する(afaik)ものです。これは、クッキーに何か問題があることを示唆しています。
私はブラウザをチェックしてクッキーが設定されているので、私はコードのすべての部分を読み飛ばして、チュートリアルをすべて私が知る限り正確に複製します。
私には何か他のものがありますか?あなたはログインしていない間、あなたのスペックypuで
module SessionsHelper
def sign_in user
# rails represents cookies as a hash and deals with the conversion for us
# making the cookie "signed" makes it impervious to attack
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
# this line calls the assignment operator below
self.current_user = user
end
def current_user=(user)
@current_user = user
end
# this is a getter method
def current_user
# this sets @current_user = to the user corresponding to the remember token
# but only if @current user is undefined. ie it only works once
@current_user ||= user_from_remember_token
end
def signed_in?
# return true if current_user is not nil
!current_user.nil?
end
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
def current_user? user
# returns true if the user object == the current_user object
user == current_user
end
def authenticate
deny_access unless signed_in?
end
def deny_access
store_location
# this is a shortcut for flash notices: flash[:notice] = "Please sign in to access this page."
redirect_to signin_path, :notice => "Please sign in to access this page."
end
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
clear_return_to
end
private
def user_from_remember_token
# the * allows us to give a 2 element array to a method expecting 2 seperate arguments
User.authenticate_with_salt(*remember_token)
end
def remember_token
# return [nil, nil] if the :remember_token cookie is nil
cookies.signed[:remember_token] || [nil, nil]
end
def store_location
# stores the url the browser was requesting
session[:return_to] = request.fullpath
end
def clear_return_to
session[:return_to] = nil
end
end
あなたは、男性の間で伝説です。 –
あなたのコメントは私の一日でした。 :) – tjeden