2014-10-16 197 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