Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec - Testing strong parameters

I am using the strong_parameters gem in my controllers, but I'm having a hard time understanding how I would test it.

Here's an example of my setup

class UserController < ActionController::Base
  include ActiveModel::ForbiddenAttributesProtection

  def create
    @user = User.new(user_params)
    if @user.save
      ...
    end
  end

  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :username, :email)
  end
end

I want to test the user_params method to make sure that it is correctly filtering out malicious key/value pairs, but can't figure out how to do it. Has anyone else been through this?

like image 297
Bryce Avatar asked May 15 '13 20:05

Bryce


2 Answers

You can stub the params hash as

params = ActionController::Parameters.new(your_hash)

This is the class that your URL params are being converted to in your controller, and it gives you the require and permit methods.

I personally extract the functionally out into a new class to handle the authorization policy.

like image 112
cpuguy83 Avatar answered Sep 23 '22 13:09

cpuguy83


Modify this according to your need,

describe "create action" do
    it 'creates a user' do
      User.should_receive(:create).
        with({name: 'Alan D'}.with_indifferent_access)
      post :create, user:
        { first_name: 'Alan', last_name: 'Donald', username: 'alan77', email: '[email protected]' }
    end
end

or other alternative solution to this problem is:

describe UsersController::UserParams do
  it 'cleans the params' do
    params = ActionController::Parameters.new(user: {foo: 'bar', name: 'baz'})
    user_params = UsersController::UserParams.build(params)
    expect(user_params).to eq({name: 'baz'}.with_indifferent_access)
  end
end
like image 25
Nimish Avatar answered Sep 21 '22 13:09

Nimish