Ruby on rails NoMethodError:未定义的方法'id';零级:零级
我是Rspec的新手,我正在尝试做TDD。在应用程序控制器中,我有一个名为set current user的方法Ruby on rails NoMethodError:未定义的方法'id';零级:零级,ruby-on-rails,ruby,rspec,rspec-rails,Ruby On Rails,Ruby,Rspec,Rspec Rails,我是Rspec的新手,我正在尝试做TDD。在应用程序控制器中,我有一个名为set current user的方法 class ApplicationController < ActionController::Base protect_from_forgery with: :exception protected def set_current_user @current_user ||= User.find_by_session_token(cooki
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
protected
def set_current_user
@current_user ||= User.find_by_session_token(cookies[:session_token])
redirect_to login_path unless @current_user
end
end
当我尝试运行规范时,会出现以下错误:
Failure/Error: if @blog.user_id != @current_user.id
NoMethodError:
undefined method `id' for nil:NilClass
有人知道如何在这方面帮助我吗?非常感谢您的帮助。
@current\u user
在您的测试中为零
你的问题就在这里
allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)
set\u current\u user
实际上并不返回用户对象,它将一个对象分配给@current\u user
变量,然后可能重定向
更重要的是,rails以这种方式设置用户:
class ApplicationController < ActionController::Base
before_action :verify_current_user!
def current_user
@current_user || User.find_by_session_token(cookies[:session_token])
end
def verify_current_user!
redirect_to login_path unless current_user
end
end
class ApplicationController
然后,在引用当前登录用户时,调用current\u user
方法。该值将被记录,因此不会有性能损失。当您在测试中尝试时,您还可以存根当前用户
方法。在控制器中,始终调用current\u user
,而不是@current\u user
allow_any_instance_of(ApplicationController).to receive(:set_current_user).and_return(fuser)
class ApplicationController < ActionController::Base
before_action :verify_current_user!
def current_user
@current_user || User.find_by_session_token(cookies[:session_token])
end
def verify_current_user!
redirect_to login_path unless current_user
end
end