Add documentation about tests customization

This commit is contained in:
Javi Martín
2024-08-19 19:04:29 +02:00
parent 64d6460215
commit 3a01e171b8
8 changed files with 156 additions and 0 deletions

View File

@@ -40,6 +40,7 @@
* [Other Ruby classes (GraphQL, lib, mailers, builders)](customization/ruby.md) * [Other Ruby classes (GraphQL, lib, mailers, builders)](customization/ruby.md)
* [Gems](customization/gems.md) * [Gems](customization/gems.md)
* [Application configuration](customization/application.md) * [Application configuration](customization/application.md)
* [Tests](customization/tests.md)
* [Technical Features](features/features.md) * [Technical Features](features/features.md)
* [OAuth](features/oauth.md) * [OAuth](features/oauth.md)

View File

@@ -12,3 +12,4 @@
* [Other Ruby classes (GraphQL, lib, mailers, builders)](ruby.md) * [Other Ruby classes (GraphQL, lib, mailers, builders)](ruby.md)
* [Gems](gems.md) * [Gems](gems.md)
* [Application configuration](application.md) * [Application configuration](application.md)
* [Tests](tests.md)

View File

@@ -40,3 +40,13 @@ There are also files where you can apply some customizations:
* `config/environments/custom/staging.rb` * `config/environments/custom/staging.rb`
* `config/environments/custom/test.rb` * `config/environments/custom/test.rb`
* `Gemfile_custom` * `Gemfile_custom`
## Running the tests
When customizing the code, it is **very important** that all the tests in your test suite are still passing. If not, there will be issues when upgrading to a new version of Consul Democracy (or even when updating the custom changes) that won't be detected until the code is running on production. Consul Democracy includes more than 6000 tests checking the way the application behaves; without them, it'd be impossible to make sure that new code doesn't break any existing behavior.
So, first, make sure you've [configured your fork](../getting_started/configuration.md) so it uses a continuous integration system that runs all the tests whenever you make changes to the code. When changing the code, we recommend opening pull requests (a.k.a. merge requests) using a development branch so the tests run before the custom changes are added to the `master` branch.
Then, if some tests fail, check one of the tests and see whether the test fails because the custom code contains a bug or because the test checks a behavior that no longer applies due to your custom changes (for example, you might modify the code so only verified users can add comments, but there might be a test checking that any user can add comments, which is the default behavior). If the test fails due to a bug in the custom code, fix it ;). If it fails due to a behavior that no longer applies, check the [tests customization](tests.md) section.
We also **strongly recommend adding tests for your custom changes**, so you'll have a way to know whether these changes keep working when upgrading to a new version of Consul Democracy.

View File

@@ -0,0 +1,66 @@
# Customizing tests
Tests check whether the application behaves as expected. For this reason, it is **extremely important** that you write tests for all the features you introduce or modify. Without tests, you'll have no reliable way to confirm that the application keeps working as expected whenever you change the code or upgrade to a new version of Consul Democracy. Consul Democracy contains more than 6000 tests checking the way the application behaves; without them, it'd be impossible to make sure that new code doesn't break any existing behavior.
Since running the tests on your development machine might take more than an hour, we recommend [configuring your fork](../getting_started/configuration.md) so it uses a continuous integration system that runs all the tests whenever you make changes to the code. When changing the code, we recommend running the tests in a development branch by opening pull requests (a.k.a. merge requests) so the tests run before the custom changes are added to the `master` branch.
Then, if some tests fail, check one of the tests and see whether the test fails because the custom code contains a bug or because the test checks a behavior that no longer applies due to your custom changes (for example, you might modify the code so only verified users can add comments, but there might be a test checking that any user can add comments, which is the default behavior). If the test fails due to a bug in the custom code, fix it ;). If it fails due to a behavior that no longer applies, then you'll have to change the test.
Changing a test is a two-step process:
1. Make sure the test checking the default behavior in Consul Democracy isn't run anymore
2. Write a new test for the new behavior
For the first step, add a `:consul` tag to the test or block of tests. For example, let's check this code:
```ruby
describe Users::PublicActivityComponent, controller: UsersController do
describe "follows tab" do
context "public interests is checked" do
it "is displayed for everyone" do
# (...)
end
it "is not displayed when the user isn't following any followables", :consul do
# (...)
end
it "is the active tab when the follows filters is selected", :consul do
# (...)
end
end
context "public interests is not checked", :consul do
it "is displayed for its owner" do
# (...)
end
it "is not displayed for anonymous users" do
# (...)
end
it "is not displayed for other users" do
# (...)
end
it "is not displayed for administrators" do
# (...)
end
end
end
end
```
In the first context, only the first test will be executed. The other two tests will be ignored because they contain the `:consul` tag.
The second context contains the `:consul` tag itself, so none of its tests will be executed.
Remember: whenever you add a `:consul` tag to a test because the application no longer behaves as that test expects, write a new test checking the new behavior. If you don't, the chances of people getting 500 errors (or, even worse, errors that nobody notices) when visiting your page will dramatically increase.
To add a custom test, use the custom folders inside the `spec/` folder:
* `spec/components/custom/`
* `spec/controllers/custom/`
* `spec/models/custom/`
* `spec/routing/custom/`
* `spec/system/custom/`

View File

@@ -40,6 +40,7 @@
* [Otras clases de Ruby (GraphQL, lib, mailers, builders)](customization/ruby.md) * [Otras clases de Ruby (GraphQL, lib, mailers, builders)](customization/ruby.md)
* [Gemas](customization/gems.md) * [Gemas](customization/gems.md)
* [Configuración de la aplicación](customization/application.md) * [Configuración de la aplicación](customization/application.md)
* [Tests](customization/tests.md)
* [Funcionalidades Técnicas](features/features.md) * [Funcionalidades Técnicas](features/features.md)
* [OAuth](features/oauth.md) * [OAuth](features/oauth.md)

View File

@@ -12,3 +12,4 @@
* [Otras clases de Ruby (GraphQL, lib, mailers, builders)](ruby.md) * [Otras clases de Ruby (GraphQL, lib, mailers, builders)](ruby.md)
* [Gemas](gems.md) * [Gemas](gems.md)
* [Configuración de la aplicación](application.md) * [Configuración de la aplicación](application.md)
* [Tests](tests.md)

View File

@@ -40,3 +40,13 @@ Aparte de estos directorios, también puedes utilizar los siguientes ficheros:
* `config/environments/custom/staging.rb` * `config/environments/custom/staging.rb`
* `config/environments/custom/test.rb` * `config/environments/custom/test.rb`
* `Gemfile_custom` * `Gemfile_custom`
## Ejecutar los tests
Al personalizar el código, es **muy importante** que todos los tests de la aplicación sigan pasando. En caso contrario, habrá fallos al actualizar a una nueva versión de Consul Democracy (o incluso al actualizar los cambios personalizados) y estos fallos no serán detectados hasta que el código esté ya ejecutándose en producción. Consul Democracy incluye más de 6000 tests que comprueban la manera en que se comporta la aplicación; sin ellos, sería imposible asegurarse de que el código nuevo no rompe comportamientos existentes.
Así que, en primer lugar, asegúrate de haber [configurado tu "fork"](../getting_started/configuration.md) para que utilice un sistema de integración continua que ejecute todos los tests cada vez que hagas cambios en el código. Recomendamos ejecutar estos tests en una rama de desarrollo abriendo una "pull request" (también llamada "merge request") para que los tests se ejecuten antes de que los cambios personalizados se añadan a la rama `master`.
En caso de que alguno de los tests falle, echa un vistazo a uno de los tests y comprueba si falla por un fallo en el código personalizado o porque el test comprueba un comportamiento que ha cambiado con los cambios personalizados (por ejemplo, puede que modifiques el código para que solamente los usuarios verificados puedan añadir comentarios, pero puede que haya un test que compruebe que cualquier usuario puede añadir comentarios, ya que es el comportamiento por defecto). Si el test falla debido a un fallo en el código personalizado, arréglalo ;). Si falla debido a un comportamiento que ha cambiado, consulta la sección de [personalización de tests](tests.md).
**Recomendamos encarecidamente añadir tests a tus cambios personalizados** para que tengas una forma de comprobar si estos cambios siguen funcionando cuando actualices a una nueva versión de Consul Democracy.

View File

@@ -0,0 +1,66 @@
# Personalización de tests
Los tests comprueban que la aplicación se comporta de la manera esperada. Por esta razón, es **extremadamente importante** que escribas tests para todas las funcionalidades que añadas o modifiques. Sin tests, no tendrás una manera fiable de confirmar que la aplicación sigue comportándose correctamente cuando cambias el código o cuando actualizas a una nueva versión de Consul Democracy. Consul Democracy incluye más de 6000 tests que comprueban la manera en que se comporta la aplicación; sin ellos, sería imposible asegurarse de que el código nuevo no rompe comportamientos existentes.
Como ejecutar los tests en tu máquina de desarrollo puede llevar más de una hora, recomendamos [configurar tu "fork"](../getting_started/configuration.md) para que use un sistema de integración continua que ejecute todos los tests cada vez que hagas cambios en el código. Recomendamos ejecutar estos tests en una rama de desarrollo abriendo una "pull request" (también llamada "merge request") para que los tests se ejecuten antes de que los cambios personalizados se añadan a la rama `master`.
En caso de que alguno de los tests falle, echa un vistazo a uno de los tests y comprueba si falla por un fallo en el código personalizado o porque el test comprueba un comportamiento que ha cambiado con los cambios personalizados (por ejemplo, puede que modifiques el código para que solamente los usuarios verificados puedan añadir comentarios, pero puede que haya un test que compruebe que cualquier usuario puede añadir comentarios, ya que es el comportamiento por defecto). Si el test falla debido a un fallo en el código personalizado, arréglalo ;). Si falla debido a un comportamiento que ha cambiado, tendrás que cambiar el test.
Cambiar un test es un proceso que consiste en dos pasos:
1. Asegurarse de que el test que comprueba el comportamiento por defecto de Consul Democracy deja de ejecutarse
2. Escribir un nuevo test para el nuevo comportamiento
Para el primer paso, añade una etiqueta `:consul` al test o al bloque de tests. Como ejemplo, veamos este código:
```ruby
describe Users::PublicActivityComponent, controller: UsersController do
describe "follows tab" do
context "public interests is checked" do
it "is displayed for everyone" do
# (...)
end
it "is not displayed when the user isn't following any followables", :consul do
# (...)
end
it "is the active tab when the follows filters is selected", :consul do
# (...)
end
end
context "public interests is not checked", :consul do
it "is displayed for its owner" do
# (...)
end
it "is not displayed for anonymous users" do
# (...)
end
it "is not displayed for other users" do
# (...)
end
it "is not displayed for administrators" do
# (...)
end
end
end
end
```
En el primer bloque de tipo "context", solamente el primer test se ejecutará. Los otros dos tests no se ejecutarán ya que contienen la etiqueta `:consul`.
El segundo bloque de tipo "context" contiene la etiqueta `:consul` en el propio bloque, con lo que ninguno de sus tests se ejecutarán.
Recuerda: cuando añadas una etiqueta `:consul` a un test porque la aplicación ya no se comporta como describe ese test, escribe un nuevo test comprobando el nuevo comportamiento. De no hacerlo, la probabilidad de que la gente que visita tu página se encuentre errores 500 (o, peor aún, errores de los que nadie se da cuenta) aumentará de manera drástica.
Para escribir un test personalizado, utiliza los directorios `custom` dentro de `spec/`:
* `spec/components/custom/`
* `spec/controllers/custom/`
* `spec/models/custom/`
* `spec/routing/custom/`
* `spec/system/custom/`