9
  • rails 5.0.0.1
  • rspec 3.5

I have inherited a code base. I am busy writing integration tests to tie down the app functionality before I consider refactoring.

I have the following lines in a controller concern before_action. It seems to read the request body. The json value here is used to extract an identifier used to authenticate the request.

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

I need to test that the authentication happens correctly. How can I set the request.body for a GET request spec?

JSON C11
  • 11,272
  • 7
  • 78
  • 65
Apie
  • 6,371
  • 7
  • 27
  • 25

2 Answers2

6

I think you should be able to do this via the request env RAW_POST_DATA

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

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

Community
  • 1
  • 1
hajpoj
  • 13,299
  • 2
  • 46
  • 63
2

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

or just

post "/widgets", params: '{ "widget": { "name":"My Widget" } }'
  • 1
    Seems like this isn't really answering OP's question? OP is asking about how to get the body and the example here doesn't include the body (the production code in OP's example doesn't refer to params). – Stephen Mariano Cabrera Jun 10 '22 at 20:09
  • In Rails, you can access attributes of the body via `params` – Kieran101 Jul 24 '23 at 02:18