0

I'm using Test::Unit in an old Rails app (3.2.22) and I'm trying to test a service class that hits an external api.

I'm using webmock and trying to get a json file fixture working, but I keep getting parsing errors from the json file.

My test stub looks like this:

response_data = fixture_file_upload('easypost/order_response.json')
stub_request(:post, 'https://api.easypost.com/v2/orders').
  to_return(:status => 200, :body => File.read(response_data))

My order_response.json file looks like this:

{
  'mode':'test',
  'reference':'Order',
  'is_return':false,
  'options':{'currency':'USD','label_date':null}
}

When I run the tests, I get a parse error:

JSON::ParserError: 757: unexpected token at '{'mode':'test','reference':'Order','is_return':false,'options':{'currency':'USD','label_date':null}}'

What is going on?

UPDATE:

Got it working by using double quotes in the JSON file:

{
  "mode":"test",
  "reference":"Order",
  "is_return":false,
  "options":{"currency":"USD","label_date":null}
}

Could anyone explain why this is necessary?

oolong
  • 665
  • 6
  • 20

2 Answers2

1

From the fine specification:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

and and object is a set of key/value pairs where the keys are strings:

enter image description here

That means that this:

{
  'mode':'test',
  'reference':'Order',
  'is_return':false,
  'options':{'currency':'USD','label_date':null}
}

is not JSON because JSON strings use double quotes and only double quotes, that's just something that sort of looks like JSON. When you switch to double quotes for your strings:

{
  "mode":"test",
  "reference":"Order",
  "is_return":false,
  "options":{"currency":"USD","label_date":null}
}

then you have JSON and everything should work.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
0

This is to make it simpler and to avoid having to have another escape method for javascript reserved keywords

I think this post might be helpful in understanding the need for quotations (and also where I found the above quote): JSON Spec - does the key have to be surrounded with quotes?

Community
  • 1
  • 1
null
  • 162
  • 5