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

标签 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 ?

谢谢。

最佳答案

您可以在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/

相关文章:

ruby-on-rails - rails : How to group records that have the same Date (month day year) for a Datetime field?

ruby-on-rails - capybara 不点击链接

ruby-on-rails - 从现在开始获得明年的正确方法

ruby-on-rails - Ruby 挽救多个特定错误

ruby - Ruby 导入的方法总是私有(private)的吗?

ruby-on-rails - Rails 4 多对多关联不起作用

ruby-on-rails - 之后(:each) vs after(:all) in Rails rspec

ruby - "wrong number of arguments"错误的 RSpec 测试在某些环境中失败

ruby-on-rails - Rails Assets 管道和摘要值

ruby-on-rails - Factory Girl 序列在 autospec 下失败