alto/assert_json

JSON collections

Closed this issue · 8 comments

I don't think this is maintained anymore. But here it goes: How do I assert JSON collections? In your example:

# => @response.body= '{"key":[{"inner_key1":"value1"},{"inner_key2":"value2"}]}'

But what if my collection uses this format:

# => @response.body= '[{"id"=>1, "key"=>"test", "name"=>"test"}, {"id"=>2, "key"=>"test", "name"=>"test"}]'
alto commented

It's still maintained. I'll take a look into it :)

I also tried another JSON response. For example:

# => @response.body= '{"keys":[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]}'
assert_json(@response.body) do
   has 'keys' do
      has 'key1', 'value1'
      has 'key2', 'value2' # when I add the second element I get: no element left, seems like a bug.
   end
end

How would I ignore certain parts of my collection?

alto commented

I'm trying to answer the following questions:

  1. how do I test an array of hashes like '[{"id":1, "key":"test", "name":"test"}, {"id":2, "key":"test", "name":"test"}]'?
  2. how do I test an array of hashes nested within a hash like '{"keys":[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]}'?
  3. how do I skip items of a collection?
alto commented

Regarding question 2:

assert_json '{"keys":[{"key1":"value1"},{"key2":"value2"},{"key3":"value3"}]}' do
  has 'keys' do
    has 'key1', 'value1'
    has 'key2', 'value2'
    has 'key3', 'value3'
  end
end

works fine for me.

@alto: Thanks for looking into this. Much appreciated. I didn't provide the correct example. Try this one:

assert_json('{"keys":[{"key1":"value1","key2":"value2","key3":"value3"}]}') do
    has 'keys' do
        has 'key1', 'value1'
        has 'key2', 'value2'
        has 'key3', 'value3'
    end
end

My bad. I probably should be using has 'key1', 'value1', 'key2', 'value2' etc. Sorry you can ignore this question.

alto commented

I just released version 0.2.0, which includes support for array items. As you can see from the README you can now do

assert_json '[{"id":1, "key":"test", "name":"test"}, {"id":2, "key":"test", "name":"test"}, {"id":3, "key":"test", "name":"test"}]' do
  item 0 do
    has 'id', 1
    has 'key', 'test'
    has 'name', 'test'
  end
  item 2 do
    has 'id', 3
  end
end

which provides answers to questions 1 and 3 😎

@alto. Awesome. Thanks!