Validating JSON with RSpec and pathy - twoism*
While building out our API I have at times needed to validate the JSON that we are returning from endpoints or as object representations in the to_json method of our models. Typically I would just parse the returned JSON string and test the resulting value like so.
# contrived rspec but you get the idea before do @post = Post.new(:title => "Yup, I'm a post") @parsed_json = JSON.parse(@post.to_json) end it "should include :title in it's JSON representation" do @parsed_json['title'].should == @post.title end
That works fine and all but once you start validating a model this becomes terribly repetitive and a chore to maintain. After adding a quick patch to Object and a bit of yack shaving, I decided to give it gem cred and publish it.
Enter Pathy
Pathy adds a few convenience methods that make validating the JSON version of an object stupid easy.
Example
require 'pathy' Object.pathy! # add the methods to all Objects @json = %[ { "string" : "barr", "number" : 1, "array" : [1,2,3], "hash" : {"one":{"two" : 2}} } ] @obj = JSON.parse(@json) puts @obj.at_json_path("number") => 1 puts @obj.at_json_path("array.1") => 2 puts @obj.at_json_path("hash.one.two") => 2
Rspec Matcher
it "should work as rspec matcher" do @obj.should have_json_path "hash.one" end
Installation
gem install pathy