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":"xyz@example.com"}' 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":"xyz@example.com"}'

which results in a HTTP status of 400.

jottr
  • 3,256
  • 3
  • 29
  • 35
  • http://stackoverflow.com/questions/14775998/posting-raw-json-data-with-rails-3-2-11-and-rspec – Tom Hert Oct 16 '14 at 21:19
  • that fixed it. If you write it as a reply, I'll accept it. – jottr Oct 16 '14 at 21:22
  • Actually your first comment, (which you sadly deleted) was the working answer: ` post users_path, user: {name: "Test", email: "xyz@example.com" }` There seems to be no need to pass the CONTENT_TYPE. – jottr Oct 16 '14 at 21:47
  • because after that I found the same question, just linked that and flagged your questions as duplicity. – Tom Hert Oct 16 '14 at 21:49

2 Answers2

2

Here is your answer:

post users_path, :user => {"name":"xyz","email":"xyz@example.com"}, { '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":"xyz@example.com"}' , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }

Hope that works for you! Cheers, Jan

jfornoff
  • 1,368
  • 9
  • 15