← Back to Upcase

Confused about parsing a stubbed API response in Webmock

(Dan Weaver) #1

When I use Mandrill to send emails a successful API response is something like this:

[{"email"=>"email@example.com", "status"=>"sent", "_id"=>"1234", "reject_reason"=>nil}]

In my controller I check for success by looking for a nil value on reject_reason:

@success = result[0]['reject_reason'].nil?

When I use Webmock to stub the network request and return a success message:

stub_request(:post, "https://mandrillapp.com/").to_return(:status => 200, :body => "[{\"reject_reason\":\"nil\"}]", :headers => {})

the reject_reason value comes back as a "nil" string rather than a NilClass so the test fails.

How do I parse this stubbed response so that I get a NilClass the same as a real request response?

I want to turn this:

[{"reject_reason":"nil"}]

into this:

[{"reject_reason":nil}]

(Geoff Harcourt) #2

nil is a Ruby concept. If the feed from Mandrill is JSON, you need to have the empty value be null, and it shouldn’t be surrounded by quotes.

Does Mandrill return a non-200 status for rejected requests? That might be a cleaner way to check for problems that wouldn’t require checking for nil.

(Dan Weaver) #3

Hi @geoffharcourt, I did try removing the quotes around the nil in the stubbed response but it throws an error:

:body => "[{\"reject_reason\":nil}]" # no quotes around nil
# => JSON::ParserError: 399: unexpected token at '{"reject_reason":nil}]'

I’ve tried to find info on Mandrill’s failure responses but not been able to get a definitive list. I’m thinking I might check for a success/failed email send by using the status: sent part of the response instead of the reject_reason. Then I’m just dealing with a straight-up string every time, regardless of environment.

Alternatively I’ll could initiate as many failing Mandrill requests as I can think of and note the responses.

I was just hoping to find a way to get a stubbed response from Webmock in exactly the same format as the standard Mandrill response but it seems that the Webmock response won’t allow a nil or null concept since everything has to be quoted.

Thanks for your help.

(Geoff Harcourt) #4

Hi @weavermedia, the nil needs to be null, since JSON is JavaScript (and has no nil). Before escaping for quotes, try putting your response through a JSON linter. Here’s the one I use sometimes: