JSON data for rspec tests
Solution 1
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.
Solution 2
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
Solution 3
Actually you can do the following with factorygirl.
factory :json_data, class: OpenStruct do
//fields
end
FactoryGirl.create(:json_data).marshal_dump.to_json
mrzasa
Updated on August 20, 2022Comments
-
mrzasa over 1 year
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
. -
Daniel Costa over 5 yearsWhere are you putting this helper? rails_spec.rb?
-
Mario Pérez Alarcón over 5 years@DanielCosta I have a module helpers at
spec/support/helpers.rb
. Then in therails_helper
I include them withconfig.include Helpers
-
cdmo almost 4 yearsThis is a very nice convenience, you can also just inline it in your specs as needed, very simple