Assuming the result is in JSON format, as a list of objects, each representing a user, example:
[{"nome": "João", "idade": 26}, {"nome": "Maria", "idade": 19}]
You can get the body of the answer with response.body
, read the JSON document and check its format. Something similar to this:
describe "GET 'index'" do
it "returns a valid list of users" do
get 'index'
expect(response).to be_success
# processar o JSON e se certificar de que é válido
doc = nil
expect {doc = JSON.parse(response.body)}.not_to raise_error(JSON::ParserError)
# é uma lista
expect(doc).to be_kind_of(Array)
# onde cada elemento da lista...
doc.each do |user|
# é um objeto
expect(user).to be_kind_of(Hash)
# com "nome" e "idade"
expect(user).to have_key("nome")
expect(user).to have_key("idade")
# sendo uma string e um inteiro
expect(user["nome"]).to be_kind_of(String)
expect(user["idade"]).to be_kind_of(Integer)
end
end
end
It depends on how exact and restricted you want your test. You can still check things as if the ages are positive, or if there are others Keys besides the "name" and "age".
See more details on list of expectations.
What exactly is the user list you expect? A JSON/XML document? A HTML page with layouts?
– Guilherme Bernal
I thought of a Json object. The return would be a Json object.
– Luiz Picolo
You can give an example?
– Guilherme Bernal
For example, my method should return a JSON in this format:
{'name': 'Luiz Picolo', 'account': '123456789'}
. Of course the content of each attribute would not be fixed.– Luiz Picolo