【问题标题】:Request spec: How to create a new user via POST request?请求规范:如何通过 POST 请求创建新用户?
【发布时间】:2014-10-16 21:12:38
【问题描述】:

给定以下控制器:

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。

【问题讨论】:

  • 修复了它。如果你写它作为回复,我会接受它。
  • 实际上,您的第一条评论(您遗憾地删除了)是有效的答案:` post users_path, user: {name: "Test", email: "xyz@example.com" }` 似乎无需传递 CONTENT_TYPE。
  • 因为在那之后我发现了相同的问题,只是将其链接起来并将您的问题标记为重复。

标签: ruby-on-rails json http rspec


【解决方案1】:

这是你的答案:

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

【讨论】:

  • 我刚刚注意到,这会导致错误:syntax error, unexpected ':', expecting =&gt; (SyntaxError) ...post users_path, user: {"name":"xyz","email":"xyz@example.co... 另请参阅我的问题下的 cmets 以供参考。
  • 已更新,现在应该可以了
  • 不。问题仍然存在。
【解决方案2】:

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

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

希望对你有用! 干杯,简

【讨论】:

  • 谢谢 Jan. Toms 上面的评论实际上已修复它。
  • 太棒了!很高兴我们把它排除在外!
猜你喜欢
  • 2015-02-23
  • 1970-01-01
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多