【发布时间】:2015-11-08 21:05:19
【问题描述】:
我正在浏览 Michael Hartl 的 Ruby on Rails 教程,遇到了一个我无法解决的问题。由于我不明白的原因,编辑用户 (users_edit_test.rb) 的测试失败了。由于本教程主要是复制代码的练习,如果已经检查并仔细检查了我的打字,但我找不到我搞砸的地方。而且,更重要的是,我想了解发生了什么。您能提供的任何帮助将不胜感激。
错误消息(包括在下面)似乎表明测试正在启动用户控制器 (users_controller.rb) 中的 edit 方法,该方法又会启动同一控制器中的私有 user_params 方法。 user_params 方法设置需要 user 参数的强参数,并允许 name、email、密码 和 password_confirmation 参数。测试运行时user参数不存在,所以返回错误。
我的第一个问题是,“user 参数是什么?” name、email、password 和 password_confirmation 参数均引用 users 中的列strong> 数据库,还有一个 id 列。但是没有 user 列。测试和控制器都有一个 @user 变量。那是 user 参数吗?这似乎没有意义,因为我应该能够随心所欲地调用变量,对吧?我觉得这里有一些基本的东西我没有得到,如果我得到了,我可以解决这个问题并回答第二个问题,“我搞砸了什么/如何解决这个问题?”,我自己。
users_edit_test.rb
require 'test_helper'
class UsersEditTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "unsuccessful edit" do
get edit_user_path(@user)
#assert_template 'users/edit'
#patch user_path(@user), user: { name: "",
# email: "foo@invalid",
# password: "foo",
# password_confirmation: "bar" }
#assert_template 'users/edit'
end
end
users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
log_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def edit
@user = User.find(params[:id])
if @user.update_attributes(user_params)
# Handle a successful update.
else
render 'edit'
end
end
private
def user_params
params.require(:user).permit(:name,
:email,
:password,
:password_confirmation)
end
end
users.yml
michael:
name: Michael Example
email: michael@example.com
password_digest: <%= User.digest('password') %>
测试输出
开始
错误[“test_unsuccessful_edit”,UsersEditTest,2015-05-14 00:05:19 +0000]
test_unsuccessful_edit#UsersEditTest (1431561919.08s)
ActionController::ParameterMissing:
ActionController::ParameterMissing: 参数丢失或值为空: user
app/controllers/users_controller.rb:34:in user_params
app/controllers/users_controller.rb:24:编辑中
test/integration/users_edit_test.rb:10:in 类中的块:UsersEditTest
app/controllers/users_controller.rb:34:in user_params
app/controllers/users_controller.rb:24:编辑中
test/integration/users_edit_test.rb:10:in 类中的块:UsersEditTest27/27:
[================================================== =================]
100% 时间:00:00:00,时间:00:00:00在 0.69446 秒内完成 27 次测试,60 次断言,0 次失败,1 次错误,0 次跳过
【问题讨论】: