How to create a test with Rspec to verify user feedback?

Asked

Viewed 967 times

6

That one describe below is the default that Rspec creates. I have a hard time working with TDD (Test Driven Development) and it is difficult to understand the whole procedure. For example, I need to test that by accessing the method index, a list of users in 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
  • 1

    What exactly is the user list you expect? A JSON/XML document? A HTML page with layouts?

  • I thought of a Json object. The return would be a Json object.

  • 1

    You can give an example?

  • 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.

2 answers

4


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.

  • In this case it returns all the content, even with the rendering of the page. As I would only get the pure return of the method. Only JSON?

  • It depends.. You can extract with a regex maybe. Difficult to say anything without seeing.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.