DEV Community

Augusts Bautra
Augusts Bautra

Posted on

Rails Request specs with arbitrary JSON params

Today I encountered a need to pass arbitrary JSON as params to a request specs, as if the POST payload was just one JSON string.

One, untenable, approach would be to pass individual keys in as params, but this would break down if the JSON in payload isn't an object.

Instead, do this:

subject(:make_request) do
  post("/endpoint", params: json, headers: headers, as: :json)
end

let(:headers) { {"Content-Type" => "application/json"} }
let(:json) { {"test" => true} }
Enter fullscreen mode Exit fullscreen mode

Note that params are given a hash and the request-making post helper is given as: :json option.

Interestingly, if you turn the params hash into a JSON string, it will produce params like this:

{"_json"=>"{\"test\":true}"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)