簡體   English   中英

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時,這才似乎是一個問題。這是可以解決的問題: 如何在Rails 5的RSpec中期待Params哈希?

基本上這應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM