请求规格:如何通过POST请求创建新用户?
问题描述:
鉴于以下控制器:请求规格:如何通过POST请求创建新用户?
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":"[email protected]"}' 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":"[email protected]"}'
导致的400
答
这里是你的答案:
post users_path, :user => {"name":"xyz","email":"[email protected]"}, { 'CONTENT_TYPE' => 'application/json'}
答
HTTP状态的问题是在头内,你需要确保它指定JSON内容!
post users_path, '{"name":"xyz","email":"[email protected]"}' , { 'CONTENT_TYPE' => 'application/json', 'ACCEPT' => 'application/json' }
希望能为你效劳! 干杯,一月
http://*.com/questions/14775998/posting-raw-json-data-with-rails-3-2-11-and -spec – 2014-10-16 21:19:32
修复它。如果你把它写成答复,我会接受它。 – jottr 2014-10-16 21:22:50
是的,它在那里 – 2014-10-16 21:26:58