سؤال

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: 'mymail@yopmail.com' }
    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

I'm not sure I would test strong_parameters, which I am guessing you're using via the gem.

The gem has its own tests, so we can assume it works as expected.

This is an example of 'testing Rails', which I believe is unnecessary. I wouldn't test that attr_accessible works as advertised (Testing Rails), or attr_accessor (Testing Ruby).

IMHO, your integration tests should cover all desired instances of success/failure and implicitly cover your strong_parameter configuration.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top