gpt4 book ai didi

ruby-on-rails - Rails ActionController 参数错误

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

这是我在 users_controller.rb 中的创建方法

def create
@user = User.new(user_params)

respond_to do |format|
if @user.save
format.html { redirect_to users_url, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

private
def set_user
@user = User.find(params[:id])
end

def user_params
params.require(:user).permit(:name, :password, :password_confirmation)
end

结束

这是我的 Users_controllers_spec.rb 文件

 require 'rails_helper'

RSpec.describe UsersController, type: :controller do

describe "Post /create" do
let(:user){build(:user)}
it "should create user" do
expect(User).to receive(:new).with({name: 'Naik', password: 'secret', password_confirmation: 'secret'}).and_return(User)
post :create, user: {name: 'Naik', password: 'secret', password_confirmation: 'secret'}
expect(flash[:success]).to eq("User was successfully created.")
expect(response).to redirect_to(users_path)
end
end
end

这就是我遇到的错误。我错过了什么吗?我是 Rspec 测试的新手,所以任何关于如何解决它的建议都将不胜感激。

Anyone has faced this error before ?

谢谢。

最佳答案

您可以在ActionController::Parameters 上执行to_h。然后所有允许的参数都将在该散列中:

params = ActionController::Parameters.new({
name: 'Senjougahara Hitagi',
oddity: 'Heavy stone crab'
})
params.to_h # => {}

safe_params = params.permit(:name)
safe_params.to_h # => { name: 'Senjougahara Hitagi' }

我不是 rspec 专家,但我认为你可以做到:

expect(controller.params.to_h).to be({...})

关于ruby-on-rails - Rails ActionController 参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38606348/

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