Zack Herbert
Zack Herbert

Reputation: 960

Rails 5 testing controller unfiltered params

I have recently upgraded my application to Rails 5 and when I am testing my controller I am getting the following error: ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash.

My controller code looks like this:

def bid
  widget_mode = params.include?(:widget)
  if [email protected]?
    redirect_to '/' #go to the homepage

  elsif @auction.third_party?
    redirect_to @auction.third_party_bidding_url

  elsif current_user && current_user.clerk? &&
        [email protected]? &&
        (@auction.items_count == 1 || params["section"] == "auction") &&
        !widget_mode
    redirect_to action: 'clerk', id: @auction.id, params: params.slice(:item, :section)
  else
    #  Make sure the auction is in firebase
    exists = @auction.rt_get('updated_at').body.to_i > 0 rescue false
    @auction.queue_realtime_update unless exists
  end
end

and my test code looks like this:

test "should redirect to powerclerk if multi item auction and params section = auction" do
  sign_in users(:clerk)
  a = auctions(:kenwood_dr)
  assert a.items.count > 1, "Expected auction to have more than one item"
  get :bid, params: {id: a.id, item: a.items.first.id, section: "auction"}
  assert_redirected_to "/clerk/1?item=1&section=auction"
end

I tried adding: params.permit(:item, :section, :id, :controller, :action, :widget) to the beginning of my bid controller method and that didn't make a difference. Any insight would be appreciated.

Upvotes: 0

Views: 584

Answers (2)

coreyward
coreyward

Reputation: 80128

This error occurs when calling to_h or to_hash on an instance of ActionController::Parameters that doesn't have any permitted keys (documentation).

Since ActionController::Parameters#slice returns an instance of the same, this code does not give you a hash like it would seem: params.slice(:item, :section).

In most cases you can use permit instead of slice on parameters instances. If you ever want to bypass the safe access whitelisting of ActionController::Parameters you can use permit! and use ActionController::Parameters#slice, or if you want to convert to a hash without sanitization you can use to_unsafe_h.

Upvotes: 1

Zack Herbert
Zack Herbert

Reputation: 960

I ended up solving this by switching:

redirect_to action: 'clerk', id: @auction.id, params: params.slice(:item, :section)

to

redirect_to action: 'clerk', id: @auction.id, params: params.permit(:item, :section)

Upvotes: 0

Related Questions