mrateb
mrateb

Reputation: 2499

Rspec - Check that a field is of type json

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

Upvotes: 0

Views: 575

Answers (1)

Mehmet Adil İstikbal
Mehmet Adil İstikbal

Reputation: 600

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

Upvotes: 1

Related Questions