How to create a test with RSpec to check the return of users?

6

This describe below is the default that Rspec creates. I have a hard time working with TDD ( Test Driven Development ) and it is complicated to understand the whole procedure. For example, I need to test that when accessing the index method, a list of users in the JSON format is returned. What would be the way to implement the test for this functionality?

describe "GET 'index'" do
  it "returns http success" do
    get 'index'
    expect(response).to be_success
  end
end
    
asked by anonymous 14.01.2014 / 14:31

2 answers

4

Assuming that the result is in JSON format, as a list of objects, each representing a user, eg:

[{"nome": "João", "idade": 26}, {"nome": "Maria", "idade": 19}]

You can get the body of the response 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 narrow you want your test. You can still check things as if the ages are positive, or if there are other keys besides "name" and < p>

See more details on list of expectations >.

    
14.01.2014 / 18:12
0

Your action index:

def index
   @users = User.all
   respond_to do |format|
     format.json { render json: @users }
   end
end

You can test how many users your variable is returning:

describe "GET 'index'" do
  it "retorna uma lista de usuários" do
    user1 = User.create(:nome=>"Maria", :idade=>"19")
    user2 = User.create(:nome=>"João", :idade=>"26")

    get 'index'
    assigns(@users).size.should == 2
  end
end
    
31.01.2014 / 01:52