Ruby on Rails使用RSpec做TDD测试编辑功能遇NoMethodError如何解决
报错根本原因
undefined method 'id' for nil:NilClass 报错是因为 Category.order("id").last 返回了空值,没有取到分类记录。
具体问题点
- RSpec 每个
it测试块默认开启事务隔离,第一个测试块创建的分类数据会在该测试执行完成后自动回滚清空,第二个测试块查询数据库时没有对应记录。 - 控制器
update方法逻辑缺失,没有将表单提交的新参数更新到分类对象,无法实现编辑功能。 - 编辑页面的提交按钮默认文本为
Update Category,测试代码中匹配的Create Category无法找到对应按钮。
修复步骤
1. 调整测试用例
在全局 before 块中提前创建测试分类,保证所有测试块都能拿到有效数据:
RSpec.describe 'EditCategories', type: :system do before do driven_by(:rack_test) # 预创建测试用分类 @test_category = Category.create!(name: '测试分类') end it 'creates category, saves and shows newly created category' do visit '/' click_link 'Create Category' visit '/categories/new' fill_in 'Name', with: 'This is a category' click_button 'Create Category' expect(page).to have_content('This is a category') end it 'edits category, saves and shows edited category' do visit "/categories/#{@test_category.id}/edit" fill_in 'Name', with: 'This is a category edited' # 匹配编辑页正确的按钮文本 click_button 'Update Category' expect(page).to have_content('This is a category edited') end end
2. 修复控制器update方法
新增参数更新逻辑:
def update @category = Category.find(params[:id]) # 调用update方法传入表单参数 if @category.update(category_params) redirect_to @category else render :edit end end
内容的提问来源于stack exchange,提问作者sa0irxe
相关产品推荐
相关产品推荐

