La Electricidad Y La Electrónica Trabajo Tecnología.pdf
Curso TDD Ruby on Rails #03: Tests unitarios
1. CURSO DE TESTING OSL
12 – 16 DE ABRIL 2010
Pruebas unitarias en Ruby
con
Test::Unit
Alberto Perdomo
Web: http://albertoperdomo.net
Email: alberto.perdomo@aentos.es
Twitter: @albertoperdomo http://www.aentos.com
3. EJEMPLO DE TEST EN RUBY
Estructura mínima
require 'test/unit'
class TC_MyTest < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
def test_fail
assert(false, 'Assertion was false.')
end
end
4. ELEMENTOS: TEST CASE
→ El test case es la clase más básica.
→ Todas las pruebas heredan de TestCase
require 'test/unit'
class TC_MyTest < Test::Unit::TestCase
# def setup
# end
# def teardown
# end
def test_fail
assert(false, 'Assertion was false.')
end
end
5. ELEMENTOS: TEST FIXTURES
→ Conjunto de precondiciones para ejecutar el test
correctamente.
→ Comúnmente: datos necesarios para el test
george:
id: 1
name: George the Monkey
reginald:
id: 2
name: Reginald the Pirate
6. ELEMENTOS: TEST SUITES
→ Un test suite engloba todos los test case con fxtures en
común.
→ El orden en que estos tests se ejecutan no importa.
7. ELEMENTOS: ASERCIÓN
Condición que siempre se ha de cumplir
require 'test/unit' Otros ejemplos:
class TC_MyTest < Test::Unit::TestCase
# def setup
assert_nil
# end assert_not_nil
assert_instance_of
# def teardown
# end assert_raised
assert_nothing_raised
def test_fail
assert(false, 'Assertion was false.')
end
end
8. EJECUCIÓN DE UN TEST CASE
SETUP
require 'test/unit'
class TC_MyTest < Test::Unit::TestCase
# def setup
# end
# def teardown TEST
# end
def test_fail
assert(false, 'Assertion was false.')
end
end
TEARDOWN
9. TEST::UNIT EN RUBY ON RAILS
→ Test::Unit viene incluido y preconfgurado
→ Varios formatos para escribir los fxtures
→ Scafolds vienen con tests unitarios
10. EN RAILS: ENTORNOS
Entornos
development → para desarollar (local)
production → para producción (servidor)
test → para pruebas (local)
Cada entorno tiene su propia DB
→ Podemos crear, modifcar y eliminar registros haciendo
pruebas sin que nos afecte
11. EN RAILS: ESTRUCTURA
$ ls -F test/
fixtures/ functional/ integration/ test_helper.rb unit/
TESTS DE LOS
DATOS MODELOS
TESTS DE CONFIGURACIÓN
CONTROLADORES DE LOS TESTS
TESTS INTERACTÚANDO
CON n CONTROLADORES
12. EN RAILS: FIXTURES
→ Directorio test/fxtures
→ Formatos disponibles: YAML, CSV
→ Se cargan automáticamente
# this will return the Hash for the fixture named david
users.yml users(:david)
# this will return the property for david called id
users(:david).id
# low & behold! I am a YAML comment!
david:
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
13. EN RUBY: ASSERTIONS DE
TEST::UNIT
Assertion Propósito Ejemplo
asert(boolean, [msg]) Se asegura de que el objeto/ assert user.valid?
la expresión sea true
assert_equal( obj1, obj2, Se asegura de que obj1 == assert_equal 5, User.count
[msg] ) obj2 sea true
assert_not_equal( obj1, Se asegura de que obj1 == assert_not_equal 0,
obj2, [msg] ) obj2 sea false User.count
assert_nil( obj, [msg] ) Se asegura de que obj.nil? assert_nil user.last_login
sea true
assert_not_nil( obj, [msg] ) Se asegura de que obj.nil? assert_not_nil user.role
sea false
assert_instance_of( class, Se asegura de que obj sea assert_instance_of String,
obj, [msg] ) del tipo class result
... ... ...
Documentación online en: http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/
14. EN RAILS: ASSERTIONS
ADICIONALES
Assertion Propósito Ejemplo
assert_valid(record) Se asegura de que el assert_valid(user)
objeto record es válido
según el estándar de AR
y devuelve los mensajes
de error pertinentes en
caso de que no
assert_difference(expression Prueba la diferencia assert_difference('User.count', -1) do
delete :destroy, :id =>
s, difference = 1, message = numérica del valor de users(:one).to_param
nil) {...} retorno de una expresión
end
como resultado de la
evaluación dentro del
bloque pasado
assert_response(type, Se asegura de que la assert_response :success
message = nil) respuesta enviada por el
servidor se ajusta a la
esperada
assert_redirected_to(options Se asegura de que la assert_redirected_to users_path
= {}, message=nil) petición ha sido
redireccionada a la URL
correcta
... ... ...
15. EN RAILS: UNIT TESTS
→ Prueban los modelos.
→ En test/unit/modelo_test.rb
→ Los test cases heredan de ActiveSupport::TestCase
require 'test_helper'
class PostTest < ActiveSupport::TestCase
def test_should_not_save_post_without_title
post = Post.new
assert !post.save
end
end
16. EN RAILS: FUNCTIONALS
→ Prueban los controladores.
→ En test/functional/nombre_controller_test.rb
→ Lost test cases heredan de ActionController::TestCase
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
def test_should_get_index
get :index
assert_response :success
assert_not_nil assigns(:posts)
end
end
17. MÁS COSAS QUE PODEMOS
PROBAR CON TEST::UNIT
Vistas → presencia de determinadas etiquetas HTML
Integración → interacción con varios controladores
Rutas → comportamiento correcto de las rutas
Mailers → el envío correcto de emails
18. EN RAILS: PREPARAR LOS TESTS
Ejecutar migraciones pendientes
→ rake db:migrate
Clonar la DB de desarrollo a la DB de test
→ rake db:test:load
TODO JUNTO
→ rake db:test:prepare
19. EN RAILS: TAREAS RAKE PARA
TESTS UNITARIOS
rake db:test:clone # Recreate the test database from the current environment's database schema
rake db:test:clone_structure # Recreate the test databases from the development structure
rake db:test:load # Recreate the test database from the current schema.rb
rake db:test:prepare # Check for pending migrations and load the test schema
rake db:test:purge # Empty the test database
rake test # Run all unit, functional and integration tests
rake test:benchmark # Run tests for benchmarkdb:test:prepare / Benchmark the performance tests
rake test:functionals # Run tests for functionalsdb:test:prepare / Run the functional tests in
test/functional
rake test:integration # Run tests for integrationdb:test:prepare / Run the integration tests in
test/integr...
rake test:plugins # Run tests for pluginsenvironment / Run the plugin tests in
vendor/plugins/*/**/test...
rake test:profile # Run tests for profiledb:test:prepare / Profile the performance tests
rake test:recent # Run tests for recentdb:test:prepare / Test recent changes
rake test:uncommitted # Run tests for uncommitteddb:test:prepare / Test changes since last checkin
(only Su...
rake test:units # Run tests for unitsdb:test:prepare / Run the unit tests in test/unit
20. EN RAILS: EJECUTAR TESTs
Ejecutar un test
→ $ cd test
→ $ ruby unit/post_test.rb
Ejecutar los tests unitarios → $ rake test:units
Ejecutar los tests funcionales → $ rake test:functionals
Ejecutar todos los tests → $ rake test