2

I'm writing tests using webmock, I need to simulate the remote api to return a 400 status, with body content,

if I just change the status from 200 to 400, with a body, the status I receive becomes 200.

      let(:stub_result) { { result: 'failed', reason: 'blabla' }.to_json }
      let!(:quote_stub) {
        stub_request(:post, 'http://example.com/rest')
          .to_return(status: 400, body: stub_result)
      }

if I follow the manual and do:

stub_request(:post, 'http://example.com/rest')
          .to_return(status: [400, body: stub_result])

I get the 400 status, but the body's empty.

any ideas?

Don Giulio
  • 2,946
  • 3
  • 43
  • 82

1 Answers1

1

The syntax you are following is for custom status message. What you are looking for is this.

stub_result = { result: 'failed', reason: 'blabla' }.to_json
stub_request(:post, 'http://example.com/rest').to_return(body: stub_result, status: 400)

res = Net::HTTP.start('example.com') do |http|
  req = Net::HTTP::Post.new('/rest')
  http.request(req)
end

> res
=> #<Net::HTTPBadRequest 400  readbody=true>


> res.body
=> "{\"result\":\"failed\",\"reason\":\"blabla\"}"
Nitish Parkar
  • 2,838
  • 1
  • 19
  • 22