Rails ActionController参数错误

Rails ActionController parameters Error

这是我在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 测试的新手,所以任何关于如何解决它的建议都将不胜感激。

谢谢。

您可以在 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({...})

这似乎只有在使用 Rails 5 时才会出现问题。这是解决此问题的方法:

基本上应该是:

expect(User).to receive(:new).with(ActionController::Parameters.new( name: 'Naik', password: 'secret',password_confirmation: 'secret').permit(:name, :password, :password_confirmation)).and_return(user)
expect(user).to receive(:save).and_return(true) # stub the `save` method
post :create,  user: {name: 'Naik', password: 'secret', password_confirmation: 'secret'}
# ...and then your expectations