Testing Strong Parameters in the Rails Console

May 17, 2021

Strong Parameters define the values that are allowed to be passed on to methods like update!. This helps make sure users can't alter data they shouldn't have access to.

It can be tricky to verify what Strong Parameters will do. But to test the behavior of Strong Parameters in the Rails console, you just need to initialize an ActionController::Parameters object with your raw parameters. Then you can quickly test the behavior of methods like require and permit:

params = ActionController::Parameters.new(user: { name: 'test', admin: true })
params.require(:user).permit(:name).to_h
 => {"name"=>"test"}

This can be especially useful for arrays:

params = ActionController::Parameters.new(values: [2, 3, 5, 7])
params.permit(:values).to_h
 => {}
params.permit(values: []).to_h
 => {"values"=>[2, 3, 5, 7]}

And nested hashes:

params = ActionController::Parameters.new(a: { b: 1, c: 2 })
params.permit(:a).to_h
 => {}
params.permit(a: [:b]).to_h
 => {"a"=>{"b"=>1}}
params.permit(a: {}).to_h
 => {"a"=>{"b"=>1, "c"=>2}}


References