Testing Rails 5 API with Postman

Here is the tricky part… Testing Rails API with Postman.

If you’re using Rails you are familiar with strong parameters. With this plugin Action Controller parameters are forbidden to be used in Active Model mass-assignments until they have been whitelisted.

Why Mass-Assignment is a problem?

Mass-assignment saves the need to assign values to each attribute of the model. But, since we aren’t restricting which attributes can be set nor are we checking their values.

This enables a malicious hacker to assign any value to any attribute…

To avoid that situation from happening, strong parameters are now enables by default, what requires a clean JSON object to be passed to our Rails API only app. This is where things can become tricky when testing with Postman.

Testing the API with Postman

Let’s say that we have an app with the following Model and Controller:

Now, let’s test it using Postman!

We are going to test user creation (updating, editing would follow the same pattern).

Step 1:

Point to our server (localhost in this example) using the right port. Change the type to POST (as per CRUD rules)

Step 2:

Make sure to define the Content-Type as application/json in the Header section. This is important as we are going to pass our JSON object as a raw object in the Body of our request.

Step 3:

Per our User Model we know that we have to pass 3 parameters: email, password and password_confirmation.

So, our JSON object should look something like this:

{"email": "StrangeName@Provider.net", "password": "12345678", "password_confirmation": "12345678"}

But, if we pay attention to the strong parameters enforced in our Controller, we will notice that we are missing an element in our JSON, the user:

params.require(:user).permit(:email, :password, :password_confirmation)

What leads to think that our previously defined JSON object is not correct and should be like this:

{ "user": {"email": "Testemail@ISP.net", "password": "12345678", "password_confirmation": "12345678"}}

What translates into the following in Postman

And voilà!