简体   繁体   English

请求规范:如何通过POST请求创建新用户?

[英]Request spec: How to create a new user via POST request?

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的HTTP POST请求来创建新用户:

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. 导致HTTP状态为400。

这是您的答案:

post users_path, :user => {"name":"xyz","email":"xyz@example.com"}, { 'CONTENT_TYPE' => 'application/json'}

The problem is within the headers, you need to assure it specifies JSON content! 问题出在标题内,您需要确保它指定了JSON内容!

post users_path, '{"name":"xyz","email":"xyz@example.com"}' , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }

Hope that works for you! 希望对您有用! Cheers, Jan 一月干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM