How to set the request.body for an Rspec request spec with a GET request

10,495

Solution 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

or just

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

Solution 2

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?

Share:
10,495
Apie
Author by

Apie

Rails developer.

Updated on June 11, 2022

Comments

  • Apie
    Apie almost 2 years
    • 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?