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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With