【问题标题】:How to set the request.body for an Rspec request spec with a GET request如何使用 GET 请求为 Rspec 请求规范设置 request.body
【发布时间】:2016-11-22 17:08:01
【问题描述】:
  • 导轨 5.0.0.1
  • rspec 3.5

我继承了一个代码库。在考虑重构之前,我正忙于编写集成测试以绑定应用程序功能。

我在控制器关注before_action 中有以下几行。它似乎阅读了请求正文。这里的json 值用于提取用于验证请求的标识符。

request.body.rewind
body = request.body.read
json = JSON.parse(body) unless body.empty?

我需要测试身份验证是否正确进行。 如何为 GET 请求规范设置 request.body

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec-rails


    【解决方案1】:

    https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec

    @rails_post_5

    require "rails_helper"
    
    RSpec.describe "Widget management", :type => :request do
    
      it "creates a Widget and redirects to the Widget's page" do
      headers = { "CONTENT_TYPE" => "application/json" }
      post "/widgets", :params => '{ "widget": { "name":"My Widget" } }', :headers => headers
        expect(response).to redirect_to(assigns(:widget))
      end
    
    end
    

    或者只是

    post "/widgets", params: '{ "widget": { "name":"My Widget" } }'
    

    【讨论】:

      【解决方案2】:

      我认为你应该可以通过请求 env RAW_POST_DATA 来做到这一点

      get root_path, {}, 'RAW_POST_DATA' => 'raw json string'
      request.raw_post # "raw json string"
      

      见: How to send raw post data in a Rails functional test?

      【讨论】:

        猜你喜欢
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        相关资源
        最近更新 更多