You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
6 Hrs
14 Min
11 Seg

Listar y mostrar Post: pruebas

11/33
Resources

How to implement TDD for post listing and detailing endpoints?

Implementing endpoints for listing and displaying post details using test-driven development (TDD) can be a challenging and rewarding task. In this article, we will guide you step-by-step on how to accomplish this while maintaining TDD best practices.

First, make sure you have your test environment set up. You can create new test files in your test folder, reusing structures and focusing on the specific endpoints you want to test.

How do I build tests for post endpoints?

To build tests for post endpoints, you can follow these steps:

  1. Test start: Create tests to verify the endpoints that list and display post details.
  2. Expected HTTP status: Make sure that the responses received have the appropriate HTTP status, such as code 200 for hits.
  3. Test data: In case there is no post in the database, verify that the response is empty for lists of posts.
  4. List of articles: Implements tests to confirm that the expected list of articles is returned, using libraries such as FactoryBot to simulate data.

In the context of effective TDD testing, FactoryBot plays an essential role by allowing you to generate test data easily with let.

let(:posts) { create_list(:post, 10, published: true) }

How to work with FactoryBot and other resources?

Creating test data with FactoryBot and Faker makes it easy to simulate real scenarios. Here's how you can use these tools:

  1. Faker data: Customize your factory with Faker to generate realistic data, such as names and emails.
  2. Boolean condition: When creating a post, handle Boolean attributes properly. Avoid using presence validators, and opt for inclusion to handle values like true/false correctly.

Example of using Faker:

factory :user do email { Faker::Internet.email } name { Faker::Name.name }end
  1. Cross-references: FactoryBot also allows you to create relationships between models, referencing other factories when defining related attributes, such as users for posts.

What are some common errors and how to solve them?

When implementing tests, you are likely to face some errors. Here are some tips:

  • Validation errors: If a boolean attribute fails validation, make sure to use inclusion.
  • Failed tests: Always verify that the paths and controllers transform the expectations set by your tests.
  • Invalid data: Use Faker to ensure valid and realistic data; check the official documentation for specific details on its use.

Also, always remember to run and validate the status of your tests:

rails g factory_bot:model Post

Incorporate good debugging practices to correct errors and adapt quickly to test results. Finally, adapt tests to any changes in models or business logic to ensure robust and dynamic test coverage.

Remember, the TDD journey can have its challenges, but with practice and patience, you will be able to master this methodology and improve the quality of your developments. Keep learning, never stop testing and always keep your curiosity alive!

Contributions 16

Questions 8

Sort by:

Want to see more contributions, questions and answers from the community?

Realmente para mi ha sido difícil seguir el curso porque no siento que haya una explicación clara de porqué se debe hacer cada cosa, si uno está empezando en este mundo hay momentos en los que se siente perdido y/o estancado en el tema.
Es mi opinión, tal vez solo me pase a mi.

Yo creo que en el FactoryBot de post podrias haber usado:

[false, true].sample

en vez de el if que hiciste, es mas legible y menos redundante.

Para evitar el problema con los posts que tienen user_id en nil en FactoryBot 5, solo se tiene que agregar FactoryBot.use_parent_strategy = false
al principio del archivo de posts.rb

https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#associations

me parece mas limpio usar (rails 7):

rails console -e test

en vez de :

  RAILS_ENV=test rails c 

Para quien instaló las gemas sin el versionamiento (like me), por alguna razón el FactoryBot de última versión al hacer FactoryBot.build(:post) no genera el USER por lo que queda el post con un user_id: nil y se mantiene en valid? FALSE.

Recomiendo instalar las versiones que el profesor recomienda. O ahondar en la documentación con las versiones finales.

Cuando estamos en el ambiente de test, se podría utilizar el comando “reload!” en la consola de Rails, para refrescarla y evitar salir y volver a ejecutarla?

¿Pero ese token que el proveedor le retorna a la SPA, también se lo tiene que hacer saber a la App no es así? De otra forma… ¿el backend cómo se va a enterar que ese token que le están enviando es valido?

Para las personas que están intentando correr el comando:

FactoryBot.build(:post)

y les da el siguiente error:

gems/i18n-1.12.0/lib/i18n.rb:210:in `translate’: wrong number of arguments (given 2, expected 01) (ArgumentError)

Es por la versión de Faker que ya es antigua y no es compatible con las versiones recientes de Rails, para actualizar Faker a la versión más reciente, solamente borren la versión de Faker en su Gemfile, quedando de la siguiente forma:

group :test do
gem “factory_bot_rails”, "~> 4.0"
gem “shoulda-matchers”, "~> 3.1"
gem "faker"
gem “database_cleaner”, "~> 1.7"
end

después eliminen el archivo Gemfile.lock de su carpeta raíz del proyecto y vuelvan a correr el comando:

bundle install

Con esto ya les debería funcionar el FactoryBot.build(:post)

A la hora de correr factory en el ambiente de pruebas de la consola rails, para crear post, con el comando FactoryBot.build(:post) solo crea el post, sin el user id, para que corra correctamente utilice el comando FactoryBot,create :post ,creando correctamente el post y el user id, creo que se debe a las actualizaciones que han habido de la fecha de la grabacion del curso a la actual

Hola! Sobre el refactor que se hizo a la validación de published, encontré una mejor idea para testear esto, en vez de borrar la linea. Se puede usar el método validate_inclusion_of. Más info aquí

RSpec.describe Post, type: :model do
  describe 'validations' do
    it 'validates presence of required fields' do
      should validate_presence_of(:title)
      should validate_presence_of(:content)
      should validate_inclusion_of(:published).in_array([true, false])
      should validate_presence_of(:user_id)
    end
  end
end

Hasta aquí llego, me he frustrado a tope. Además de ser un curso antiguo, siento que la explicación no es clara (pese a que llevé los cursos previos recomendados por la ruta). De tanto pausar y buscar mejores explicaciones, estoy aprendiendo más incluso con Youtube, contenido totalmente gratuito y de calidad. Uno, al pagar por Platzi, espera recibir lo mejor, pero no es el caso.

tuve un error usando la version 5.0 de factorybot me salia KeyError (Factory not registered: “post”)
asi que volvi a la version 4.0

Entonces como haces el test con RSpec de los boolean.

Cómo hizo para hacer pasar el test de la lista de posts???
Probe con factorybot desde la consola crear 10 posts, pero cuando vuelvo a ejecutar rspec obtengo este error

Failure/Error: expect(payload.size).to eq(posts.size)
     
       expected: 10
            got: 0

corro bundle exec spec como en el minuto 11:25

pero no me salen errores, alguna idea?

Finished in 0.56855 seconds (files took 5.79 seconds to load)
5 examples, 0 failures

Direncia entre let y let!
NO olvidad que le es de RSpec

https://mixandgo.com/learn/let-vs-instance-variables-in-rspec