Rails ActionController参数错误

时间:2016-07-27 07:20:42

标签: ruby-on-rails ruby rspec rspec-rails

这是我在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 ?

谢谢。

2 个答案:

答案 0 :(得分:2)

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

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

我不是专业人士,但我认为你可以这样做:

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

答案 1 :(得分:1)

这仅在使用Rails 5时才会出现问题。以下是如何修复此问题:How to expect a Params hash in RSpec in Rails 5?

基本上应该是:

-rw-r--r--. 1 root root 52 Jul 30 19:25 my_script.sh
[rehamadel@localhost bin]$ chmod u+x my_script.sh
chmod: changing permissions of ‘my_script.sh’: Operation not permitted