简体   繁体   中英

Rails ActionController parameters Error

This is my create method in 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

end

And This is my Users_controllers_spec.rb file

 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 

And this is the error I am getting. Am I missing something? I am new to Rspec testing so any advice on how to solve it would be appreciated.

有人遇到过这个错误吗?

Thank you.

You can do to_h on the ActionController::Parameters . Then all permitted parameters will be in that hash:

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' }

I'm no rspec pro but I think you can do:

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

This seems to be an issue only when using Rails 5. Here is how this can be fixed: How to expect a Params hash in RSpec in Rails 5?

Basically this should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM