0

In Rails I have a field that is supposed to save json data. It's of type json. My current Rspec is as follows:

 it 'My field has some json data saved' do person = People.last saved_national_id_data = JSON.parse(person.raw_national_id_data) # check some attributes have proper data end 

Now here I'm assuming that the field is json. Is there a way in Rspec to check that the returned data for this field is of type json? Example:

expect(saved_national_id_data).to be_json 
1
  • There's no JSON type. Unparsed JSON is a string, parsed JSON is a Hash in Ruby. Answer below is a good direction. Commented Aug 4, 2022 at 11:14

1 Answer 1

1

You can test it like this:

unparsable_json = ":a => 'b'" expect { JSON.parse(unparsable_json)}.to_not raise_error # It will return: RSpec::Expectations::ExpectationNotMetError: expected no Exception, got #<JSON::ParserError: 859: unexpected token at ':ok => 'a'' parsable_json = "\"ok\"" expect{JSON.parse(parsable_json)}.to_not raise_error # It will pass the test 
Sign up to request clarification or add additional context in comments.

3 Comments

This is definitely a good direction, especially if JSON comes from and external system. It's possible to go further than that, and do something like expect(JSON.dump(JSON.parse(person.raw_national_id_data))).to eq person.raw_national_id_data to make sure that this JSON deserializes and serializes to the same thing. It is pretty strict though so you may run into issues.
Another way would be to apply some kind of JSON schema ruby-toolbox.com/search?q=json+schema
Thanks Mehmet this will do, and thanks @MikeSzyndel for the suggestions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.