Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Problem stubbing HTTParty request response body

5,029 views
Skip to first unread message

AngelLeroy

unread,
Nov 6, 2013, 9:57:28 PM11/6/13
to webmoc...@googlegroups.com
Hi,

I am attempting to stub a get request with HTTParty, but it's not working as I would expect.

citydeal_response = HTTParty.get "/citydeal/#{citydeal_id}" #full url provided with base_uri

Later on I'm calling this response as follows:
citydeal_response.first["merchantId"]

This works when testing against live data, but in my spec tests, it fails, likely because I can only pass a string in the body of the stub_request return:      

Live inspect:
#<HTTParty::Response:0x7f8ed149a450 parsed_response=[{\"merchantId\"=>119074}] ...
Live parsed response:
[{"dealId"=>119074}]

Test inspect:
#<HTTParty::Response:0x7fbd39ddbca8 parsed_response="[{\"merchantId\":856742}]" ...
Test parsed response:
[{"merchantId":856742}]

Current stub_request (not stubbing a return for the entire body because it's huge and I'm only working with this one part):
stub_request(:get, @get_citydeal_url).to_return(:status => 200, :body => [{"merchantId"=>856742}].to_json, :headers => {})

If I use to_json or wrap the body in '', I get IndexError: string not matched - which makes sense, as .first for this string is "[". If I don't include these, and pass an array, the error is NoMethodError: undefined method `strip' for [{"merchantId"=>856742}]:Array

What am I doing wrong here? Hopefully it's simple, because I'm stumped. Also, let me know if I can provide any additional detail. Thanks.

Bartosz Blimke

unread,
Nov 7, 2013, 2:33:50 AM11/7/13
to webmoc...@googlegroups.com
Have a look at the headers returned from live api. Probably it's returning :content_type => 'application/json' header so HTTParty knows how to parse the response to json. Your stubbed response doesn't declare this header so HTTParty treats response as a string.

Bartosz


2013/11/7 AngelLeroy <alga...@gmail.com>

--
 
---
You received this message because you are subscribed to the Google Groups "webmock-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to webmock-user...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

AngelLeroy

unread,
Nov 8, 2013, 11:24:25 AM11/8/13
to webmoc...@googlegroups.com
I knew it was a stupid mistake. Tests are working now. Thanks!

Mark Mohr

unread,
Mar 10, 2017, 11:19:58 AM3/10/17
to webmock-users
Thanks for this answer, Bartosz.  Been beating me head against the wall all day.
Reply all
Reply to author
Forward
0 new messages