如何使用GET请求为Rspec请求规范设置request.body

时间:2016-11-22 17:08:01

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

  • rails 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

2 个答案:

答案 0 :(得分:1)

我认为您应该可以通过请求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?

答案 1 :(得分:1)

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

@ rails_post_5

response.content

或只是

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