0

Given the following controller:

class UsersController < ApplicationController
      include ActionController::ImplicitRender
      include ActionController::ParamsWrapper

      wrap_parameters format: :json
      # POST /users
      # POST /users.json
      def create
        #@user = User.new(params[:user])
        @user = User.new(user_params)

        if @user.save
          render json: @user, status: :created, location: @user
        else
          render json: @user.errors, status: :unprocessable_entity
        end
      end

      private

        def user_params
          params.require(:user).permit(:name, :email)
        end
end

I am able to create a new user by sending a HTTP POST request with CURL:

curl -H "Content-Type: application/json" -d '{"name":"xyz","email":"[email protected]"}' http://myrailsapp.dev/users 

How would I craft the request spec accordingly?

  # spec/requests/users_spec.rb
  describe "POST /users" do
    it "should create a new user" do

      # FILL ME IN

      expect(response).to have_http_status(200)
    end
  end

My first idea was to add the following:

post users_path, body: '{"name":"xyz","email":"[email protected]"}'

which results in a HTTP status of 400.

jottr
  • 3,256
  • 3
  • 29
  • 35

2 Answers2

2

Here is your answer:

post users_path, :user => {"name":"xyz","email":"[email protected]"}, { 'CONTENT_TYPE' => 'application/json'}
Tom Hert
  • 947
  • 2
  • 10
  • 32
0

The problem is within the headers, you need to assure it specifies JSON content!

post users_path, '{"name":"xyz","email":"[email protected]"}' , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }

Hope that works for you! Cheers, Jan

jfornoff
  • 1,368
  • 9
  • 15