2014-10-16 199 views
0

鉴于以下控制器:请求规格:如何通过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

+0

http://stackoverflow.com/questions/14775998/posting-raw-json-data-with-rails-3-2-11-and -spec – 2014-10-16 21:19:32

+0

修复它。如果你把它写成答复,我会接受它。 – jottr 2014-10-16 21:22:50

+0

是的,它在那里 – 2014-10-16 21:26:58

回答

2

这里是你的答案:

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

我刚刚注意到,这导致了一个错误: 'syntax error,unexpected':',expected = =(SyntaxError) ... post users_path,user:{“name”:“xyz”,“email” :“[email protected] ...' 另请参阅我的问题以供参考下的评论。 – jottr 2014-10-16 21:50:23

+0

更新,现在应该是好的 – 2014-10-16 21:55:24

+0

没有问题依然存在。 – jottr 2014-10-16 22:18:50

0

HTTP状态的问题是在头内,你需要确保它指定JSON内容!

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

希望能为你效劳! 干杯,一月

+0

Thx Jan.Toms上面的评论实际上修正了它。 – jottr 2014-10-16 21:26:57

+0

太棒了!很高兴我们把它赶出去了! – jfornoff 2014-10-16 21:27:59