JSON data for rspec tests

mrzasa picture mrzasa · Jan 30, 2013 · Viewed 13k times · Source

I'm creating an API that accepts JSON data and I want to provide testing data for it.

Is there anything similar to factories for JSON data? I would like to have the same data available in an object and in JSON, so that I can check if import works as I intended.

JSON has strictly defined structure so I can't call FactoryGirl(:record).to_json.

Answer

Jesse Wolgamott picture Jesse Wolgamott · Jan 30, 2013

In cases like this, I'll create fixture files for the JSON I want to import. Something like this can work:

json = JSON.parse(File.read("fixtures/valid_customer.json"))
customer = ImportsData.import(json)
customer.name.should eq(json["customer"]["name"])

I haven't seen something where you could use FactoryGirl to set attributes, then get it into JSON and import it. You'd likely need to create a mapper that will take your Customer object and render it in JSON, then import it.