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

时间:2014-10-16 21:12:39

标签: ruby-on-rails json http rspec

给出以下控制器:

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

我可以通过发送带有CURL的HTTP POST请求来创建新用户:

curl -H "Content-Type: application/json" -d '{"name":"xyz","email":"xyz@example.com"}' http://myrailsapp.dev/users 

我如何制作相应的请求规范?

  # 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

我的第一个想法是添加以下内容:

post users_path, body: '{"name":"xyz","email":"xyz@example.com"}'

导致HTTP状态为400.

2 个答案:

答案 0 :(得分:2)

这是你的答案:

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

答案 1 :(得分:0)

问题出在标题内,您需要确保它指定JSON内容!

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

希望对你有用! 干杯,Jan