Question

I have the following rspec request test:

describe "Order Processing Statuses API" do
  # index
  let(:user_with_api) { FactoryGirl.create(:user_with_api) }
  it 'sends a list of order statuses' do
    FactoryGirl.create_list(:order_processing_status, 2)

    get '/api/v1/order_statuses', nil, 'HTTP_AUTHORIZATION'=>"Token token=\"#{user_with_api.api_keys.first.access_token}\"" 

    expect(response).to be_success            
    expect(json.length).to eq(2) 
  end
end

Where json is defined by this helper:

module Requests
  module JsonHelpers
    def json
      @json ||= JSON.parse(response.body)
    end
  end
end

How do I make sure that each object in the JSON array, just have the keys that my API wants to expose? So, in my controller I will have something like this:

render @json, only: [:id, :name]

How do I make sure that each object of the response will just have those attributes? Taking into account that when defining the object with the Factory, more attributes are added that the ones that are exposed publicly.

Was it helpful?

Solution

The matcher you want is:

expect(json.keys).to contain_exactly(:id, :name)

There is also an array match syntax:

So if you have a JSON response that looks something like:

[ "order_statuses" : 
    [ 
        { 
            "id" : "id_one",  
            "name: "a name"
        },
        { 
            "id" : "id_one",  
            "name: "a name"
        }
    ] 
]

Then your (pseudo)code might look something like:

json[ "order_statuses" ].each do |status|
    expect(status.keys).to contain_exactly( :id, :name )
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top