gpt4 book ai didi

ruby-on-rails - 测试返回参数缺失或值空

转载 作者:数据小太阳 更新时间:2023-10-29 07:52:43 26 4
gpt4 key购买 nike

我正在 RoR 4 中开发一个小型应用程序,但遇到了问题。这是我正在使用的代码:

def update
@status = current_user.statuses.find(params[:id])

if params[:status] && params[:status].has_key?(:user_id)
params[:status].delete(:user_id)
end

respond_to do |format|
if @status.update(status_params)
format.html { redirect_to @status, notice: 'Status was successfully updated.' }
format.json { render :show, status: :ok, location: @status } #Original
else
format.html { render :edit }
format.json { render json: @status.errors, status: :unprocessable_entity }
end
end
end

private
# Never trust parameters from the scary internet, only allow the white list through.
def status_params
params.require(:status).permit(:user_id, :content)
end
end

这是我正在运行的测试:

test "should not update status if nothing has changed" do
sign_in users(:sean)
patch :update, id: @status
assert_redirected_to status_path(assigns(:status))
assert_equal assigns(:status).user_id, users(:sean).id
end

当我运行测试时,这是我遇到的失败:

1) Error:
StatusesControllerTest#test_should_not_update_status_if_nothing_has_changed:
ActionController::ParameterMissing: param is missing or the value is empty: status
app/controllers/statuses_controller.rb:80:in `status_params'
app/controllers/statuses_controller.rb:51:in `block in update'
app/controllers/statuses_controller.rb:50:in `update'
test/controllers/statuses_controller_test.rb:83:in `block in <class:StatusesControllerTest>'

当我发出 puts 语句时,输出显示: {"status"=>{"content"=>"MyText"}

所以我假设参数存在并被填充。对此的任何帮助将不胜感激,因为我束手无策。这是托管代码的我的 github 的链接:

http://www.github.com/sean-perryman/treebook

最佳答案

问题出在您的测试用例 patch :update, id: @status 中。

试试这个:

补丁:更新,{id:@status.id,状态:{user_id:@status.user_id,内容:'MyText'}}

您的 Controller 更新方法要求您传入的参数为上述格式。状态 ID 的 :id 键和包含要更新的状态参数的散列的状态键。

您遇到的异常(exception)情况是您没有传入状态参数。

另外请注意,最好放置 params.require(:id) 而不是 params[:id],因为您的方法依赖于它。

关于ruby-on-rails - 测试返回参数缺失或值空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23921160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com