collectiveidea / json_spec

Easily handle JSON in RSpec and Cucumber
rubygems.org/gems/json_spec
MIT License
917 stars 114 forks source link

Extend include_json to match elements inside an array of hash #41

Closed marshallshen closed 11 years ago

marshallshen commented 11 years ago

Background: Right now include_json can't test a specific element inside a hash that is included in an array. I understand that the package comes with exclude_keys, but it'd be handy if it can only match up the elements that I care about.

Use case

Given actual (json object) and expected(hash):

JSON.parse(actual) [{"user1" => {"name" => "Mike", "gender" => "male"}}, {"user2" => {"name" => "Abby", "gender" => "female"}}]

expected {"name" => "Abby", "gender" => "female"}

actual.should include_json(expected.to_json)

false

This patch will make the following truthy:

actual.should include_json(expected.to_json)

true

marshallshen commented 11 years ago

@laserlemon , just submitted a fixed patch. https://github.com/marshallshen/json_spec/commit/8650db1adf5468af4c1609902c0a3922cd124ee4

marshallshen commented 11 years ago

Hi, any updates on this?

laserlemon commented 11 years ago

I'm still not sold on the implementation. I believe RSpec's built-in include matcher does hash subset matching. Maybe we could use that across the board rather than matching three separate cases.

marshallshen commented 11 years ago

I am not sure what you mean by hash subset matching, can you clarify?

For example

    { a: 'f', c: 'd'}.should include({a:'f'})

works, but what I think I actually need is

    { a: { e: 'f'}, c: 'd'}.should include({e:'f'})

which doesn't work.

laserlemon commented 11 years ago

In my opinion, if one of those works, the other shouldn't. Those are two totally different assertions that on the surface, should behave identically.

marshallshen commented 11 years ago

should behave identically.

Do you mean "should not"? It makes sense to me that these two assertions should NOT behave identically, but then I'm still unclear about which of the two you mean by "hash subset matching". Thanks.

laserlemon commented 11 years ago

By hash subset matching, I meant:

{one: 1, two: 2}.should include(one: 1) # => passes
marshallshen commented 11 years ago

Hi, I pushed another commit per our discussion. Here are the highlights for the updated pull request: 1) Utilize spec built-in include to perform matching 2) There are two cases where spec built-in couldn't handle:

I suspect that there might be better way to handle these two special cases, but not sure how, any suggestions on how to improve this will be much appreciated!

marshallshen commented 11 years ago

Close unreviewed pull request