Search code examples
ruby-on-railsjsontestunit

Can't correctly parse JSON fixture in tests


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?


Solution

  • 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.