[rspec-users] Test JSON with Cucumber

Zach Dennis zach.dennis at gmail.com
Mon May 11 18:42:24 EDT 2009

On Mon, May 11, 2009 at 5:31 PM, Bill Kocik <bkocik at gmail.com> wrote:
> On Mon, May 11, 2009 at 4:32 PM, Ben Mabey <ben at benmabey.com> wrote:
>> 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.
> You're absolutely correct - I think I did a poor job of asking my
> question. Maybe a more concrete example would help. Suppose I have
> this JSON:
> response:{code:'200',requestId:'1234'}
> I want to have a scenario like this in my Cucumber feature file:
> When I go to "the statuses JSON url"
> Then I should find "....." # ['response']['code']
> And I should find "....." #['response']['requestId']
> With a step definition like:
> Then /^I should find "([^\"]*)"$/ do |the_string|
>  json = ActiveSupport::JSON.decode(@response.body)
>  assert_not_nil ...... #(something with the json obect and the_string)
> end
> I don't know what goes in those blanks. Cucumber is going to give me a
> string it found with the regex, but I don't know what the string would
> look like in my "Then I should find" line in my feature file, nor what
> to do with it in my assert line in the step definition. I'm not even
> sure any of this is possible.
> Consider if I were dealing with XML instead of JSON - I could put an
> XPath expression in my "Then I should find" line, and in my step
> definition I could search the XML with the given XPath expression
> using hpricot or something. With JSON and it's resultant hash, I have
> no idea where to start...

Another options is to call #to_xml on the JSON hash returned by
#decode, and then use XPath since you seem to already know it,

> --
> Bill Kocik
> http://bkocik.net
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users

Zach Dennis
http://www.continuousthinking.com (personal)
http://www.mutuallyhuman.com (hire me)
@zachdennis (twitter)

More information about the rspec-users mailing list