【发布时间】:2021-07-28 08:55:09
【问题描述】:
总结:我是 Ruby on Rails 的新手。正在使用 rspec 为编辑功能做 TDD 的课堂作业。我遇到了这个错误:
失败/错误:访问“/categories/#{category.id}/edit” NoMethodError:未定义方法 `id' for nil:NilClass
我所做的是在 CategoriesController 中定义编辑和更新方法,但错误仍然存在。
请参考以下代码。感谢您的指导。
edit_category_spec.rb:
RSpec.describe 'EditCategories', type: :system do
before do
driven_by(:rack_test)
end
it 'creates category, saves and shows newly created category' do
# visit root route
visit '/'
#click create category link
click_link 'Create Category'
#visit categories/new page
visit '/categories/new'
#fill in form with required info
fill_in 'Name', with: 'This is a category'
#click submit button
click_button 'Create Category'
#expect page to have the content submitted
expect(page).to have_content('This is a category')
end
it 'edits category, saves and shows edited category' do
category = Category.order("id").last
visit "/categories/#{category.id}/edit"
fill_in 'Name', with: 'This is a category edited'
click_button 'Create Category'
expect(page).to have_content('This is a category edited')
end
end ```
categories_controller.rb
```class CategoriesController < ApplicationController
def index
end
def show
@category = Category.find(params[:id])
end
def new
@category = Category.new
end
def create
@category = Category.new(category_params)
if @category.save
redirect_to @category
else
render :new
end
end
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
if @category.save
redirect_to @category
else
render :edit
end
end
private
def category_params
params.require(:category).permit(:name)
end
end
【问题讨论】:
-
category = Category.order("id").last在category变量上设置nil,因为可能不存在类别 -
感谢您的洞察力。