Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON data for rspec tests

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.

like image 203
mrzasa Avatar asked Jan 30 '13 14:01

mrzasa


3 Answers

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.

like image 56
Jesse Wolgamott Avatar answered Oct 23 '22 21:10

Jesse Wolgamott


Following Jesse's advice, in Rails 5 now you could use file_fixture (docs)

I just use a little helper for reading my json fixtures:

def json_data(filename:)
  file_content = file_fixture("#{filename}.json").read
  JSON.parse(file_content, symbolize_names: true)
end
like image 17
Mario Pérez Avatar answered Oct 23 '22 21:10

Mario Pérez


Actually you can do the following with factorygirl.

factory :json_data, class: OpenStruct do 
   //fields
end

FactoryGirl.create(:json_data).marshal_dump.to_json
like image 5
Stephane Paul Avatar answered Oct 23 '22 21:10

Stephane Paul