这是我得到的错误:
Error:
ProjectsControllerTest#test_should_redirect_destroy_when_not_logged_in:
NoMethodError: undefined method `projects' for nil:NilClass
app/controllers/projects_controller.rb:39:in `project_owner'
test/controllers/projects_controller_test.rb:19:in `block (2 levels) in <class:ProjectsControllerTest>'
test/controllers/projects_controller_test.rb:18:in `block in <class:ProjectsControllerTest>'
我认为发生的事情是正确的,如果我错了,那就是当代码进入并搜索项目时,它发现用户没有登录,因此没有这样的project_owner。即使这样,project_owner对象也应该选择它并检查它是否为零,但这可能不会发生。
Projects.Controller
class ProjectsController < ApplicationController
before_action :logged_in_user, only: [:index, :show, :create]
before_action :project_owner, only: :destroy
def index
end
def show
@project = Project.find(params[:id])
end
def new
@project = Project.new
end
def create
@project = current_user.projects.build(project_params)
if @project.save
flash[:success] = "Project Created"
redirect_to @project
else
render 'new'
end
end
def destroy
@project.destroy
flash[:success] = "Project Deleted"
redirect_to request.referrer || root_url
end
private
def project_params
params.require(:project).permit(:name,:category,:picture)
end
def project_owner
@project = current_user.projects.find_by(id: params[:id])
redirect_to root_url if @project.nil?
end
end
项目模型
class Project < ApplicationRecord
before_save {name.downcase!}
belongs_to :user
default_scope -> { order(created_at: :desc) }
mount_uploader :picture, PictureUploader
validates :user_id, presence: true
validates :name && :category, presence: true
validates :name, presence: true,
uniqueness: { case_sensitive: false }
测试服
require 'test_helper'
class ProjectsControllerTest < ActionDispatch::IntegrationTest
def setup
@project = projects(:Flyingcar)
end
test "should redirect destroy when not logged in" do
assert_no_difference 'Project.count' do
delete project_path(@project)
end
assert_redirected_to login_url
end
关于它可能是什么的任何想法?
谢谢!
答案 0 :(得分:1)
此current_user错误是由project_owner方法中current_user的nil值引起的。
将此方法更改为
def project_owner
if current_user.nil?
redirect_to root_url
else
@project = current_user.projects.find_by(id: params[:id])
redirect_to root_url if @project.nil?
end
end
答案 1 :(得分:0)
在create
和project_owner
中都没有定义current_user,或者你在过滤器中是这样做的?然后你还必须为project_owner