jsonapi-rb / jsonapi-rspec

RSpec matchers for JSON:API spec
https://rubygems.org/gems/jsonapi-rspec
MIT License
123 stars 24 forks source link

Matchers to handle data arrays #27

Open BrennickL opened 3 years ago

BrennickL commented 3 years ago

Expected Behavior

Should be able to handle Arrays.

Actual Behavior

Does not handle arrays.

Steps to Reproduce the Problem

  1. Create a JSON Serialized object that has the 'data' attribute as an array.
  2. Deserialize the JSON object
  3. Pass the 'data' attribute to the matchers, either as a single node or as an array of nodes.

Specifications

stas commented 3 years ago

@BrennickL it would be great to leave a more concrete example. I'm not sure I understand fully what do you mean by data arrays.

Btw, have you seen this section? https://github.com/jsonapi-rb/jsonapi-rspec#advanced-examples

kassi commented 3 years ago

@stas I think I understand what the OPs problem is because I'm facing a similar one. According to the docs, this should work:

expect(document['data']).to have_relationship(:posts).with_data([{ 'id' => '1', 'type' => 'posts' }])

However what you get if you pass in a structure to test like

{
  "data"=> {
    "id" => ..., "type" => "...",
    "attribuites" => {...},
    "relationships" => {
      "posts": [
        { "data" => { "id" => "1", "type" => "posts" } },
        { "data" => { "id" => "2", "type" => "posts" } },
      ]
    }
  }

is

Failure/Error: expect(json["data"]).to have_relationship(:posts).with_data( [ { "id" => ...}, { "id" => "..." } ] )

     TypeError:
       no implicit conversion of String into Integer

because https://github.com/jsonapi-rb/jsonapi-rspec/blob/master/lib/jsonapi/rspec/relationships.rb#L9 can't handle arrays. It actually expects relationships[:posts] to be an object, but here it's an array.

stas commented 3 years ago

@kassi would you be kind to review this test and help me understand how's that different from your example: https://github.com/jsonapi-rb/jsonapi-rspec/blob/master/spec/jsonapi/relationships_spec.rb#L35-L42

beauby commented 3 years ago

@kassi Your input is ill-formed. Your posts should be an object containing a data member that is an array, rather than being an array containing objects with a data member:

{ "posts": 
  { "data": [
    { "id" => "1", "type" => "posts" },
    { "id" => "2", "type" => "posts" }]
  }
}

Cf. https://jsonapi.org/format/#document-resource-object-linkage