Rails 4 Api Users Post test failing

138 views Asked by At

I'm building a blog in Rails 4.2 API (for an Angular front end). I'm adding in users with devise (overkill I know), and my controller tests pass for everything. When I try a curl POST request or try to create a user from my Angular app, I get a 406 Not Acceptable status code.

Here is my create controller method:

def create
    user = User.new(user_params)
    if user.save
        render json: user, status: 201
    else
        render json: { errors: user.errors }, status: 422
    end
end

private
def user_params
    params.require(:user).permit(:email, :password, :password_confirmation)
end

I am able to create users from the rails console without a problem.

Here is the curl command I keep trying:

curl -i -H 'Accept: application/json' -H 'Content-type: application/json' -X POST -d '{"email":"[email protected]","password":"12345678","password_confirmation":"12345678"}' http://api.myapi.dev/users

and I have this resource too:

api_users POST   /users(.:format)                            api/users#create {:subdomain=>"api"}

I can update a user, and perform any other action from curl without issue, I just don't see the problem here. Any help is greatly appreciated.

1

There are 1 answers

4
Arslan Ali On BEST ANSWER

According to W3, 406 response is:

The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.

So when you use cURL, you don't need to send -H 'Accept: application/json' -H 'Content-type: application/json, Rails will automatically render the JSON result for you. Because you have only specified format.json in your controller.

Rails expects you to send the data in following way:

{ "users": { "email", "[email protected]" }, ... }

While you are not sending users when you hit the server with the cURL command.