Mass Assignment Testing

Learn to write tests for mass assignments, and how to test strong parameters.

Mass assignment testing

Mass assignment is a common Rails security issue, caused by Rails’s ability to save an arbitrary hash of attribute names and values to an instance by sending an entire hash as a parameter, as in new(params[:user]), create(params[:user]), or update_attributes(params[:user]). The security issue happens when somebody hacks a request and adds unexpected attributes to the incoming parameters, typically an attribute that we wouldn’t want an arbitrary user to change, such as User#admin or Project#public. (GitHub was famously hacked via this vector by a user who added himself as a committer to the Rails repo.)

Whitelisting attributes

Rails 4 added the concept of strong parameters to allow us to identify parts of the parameter hash from an incoming request as required or permissible. To be used in a mass assignment, the attributes need to be identified using the require or permit methods of the Rails parameter object. Attributes that aren’t whitelisted aren’t passed on to the ActiveRecord object, and they are helpfully listed in the Rails log as a warning and to make debugging these issues easier.

Strong parameters definition

The Gatherer application currently uses strong parameters in one location, TasksController#update, where there is a method that defines them:

Get hands-on with 1200+ tech skills courses.