[rspec-users] Test JSON with Cucumber

Ben Mabey ben at benmabey.com
Mon May 11 16:32:22 EDT 2009

Bill Kocik wrote:
> Hi Folks -
> I'm hoping someone has come before me in trying to do this. I want to
> use Cucumber to acceptance-test my JSON output. So far all I can do is
> validate that the JSON is valid, with this step:
> Then /^I should get valid JSON$/ do
>   assert_nothing_raised do
>     ActiveSupport::JSON.decode(@response.body)
>   end
> What I'd really like to do is be able to drill down into the JSON
> looking for the presence of certain elements in their correct places.
> For example, if my JSON is {"foo":{"bar":"baz"}} and parses out to
> {'foo' => {'bar' => 'baz'}} then I want to be able to test that
> ['foo']['bar'] gives me 'baz', or at least that ['foo']['bar'] exists.
> Unfortunately I'm not sure how to go about writing step definitions to
> do anything like this, since I haven't yet figured out a way to take a
> regular expression or string and inspect a hash with it.
> Anyone have any ideas? I could really use a brain-kick here.
> Thanks...

Well.. IIRC ActiveSupport::JSON.decode will return a ruby hash of the 
JSON, correct?  So you should be able to make expectations on it just 
like a regular hash object.

json = ActiveSupport::JSON.decode(@response.body)
json['foo']['bar'].should == 'baz'.

Does that help or am I missing something about your question?


More information about the rspec-users mailing list