0

I want to implement resetting of DB in such a way that when I execute all spec files through test runner, DB is created at the start before 1st spec file and post that after every spec file DB should reset to its original state which means the data which is created in DB due to execution of respective spec files should be removed and DB should be back to the state how it was before the execution of 1st spec file before running the next spec file. This should happen for every spec file and finally after last spec file DB should be deleted. Currently creation and deletion of DB is handled as expected in before and after hooks respectively. Will be handling reset operation in before hook itself. But how to reset the Db as expected ?

pegasus013
  • 51
  • 4
  • I do this frequently with Java and JUnit. When considering the triple A (AAA - Arrange, Act, Assert) methodology during the "Arrange" stage I ensure the system is as expected prior to the test, which usually includes deleting everything first, then adding specific data to satisfy an integration test. Since I generally test with a well-known database name I simply drop the database first which removes all traces including indexes. For completeness I also drop the database at the end. This is just cleanup. – barrypicker Nov 23 '21 at 21:22
  • @barrypicker Yes but if I delete DB after every test, then again before next test, I need to create it again and follow the same for further tests as well. I am planning to reuse the same DB which I have created before first test and reuse it for all tests just clearing the records and not the DB at these stages and finally at the end once all tests are done I'll drop it. Problem is that if I use the same DB without deleting it or clearing the records in it after my 1st test, then the data which is already created in app because of 1st test, the further test fails due to previous tests data. – pegasus013 Nov 24 '21 at 13:56
  • I guess I am not clear on why dropping the database and recreating it for every test is a problem. This approach has worked well for me. – barrypicker Nov 24 '21 at 16:07

1 Answers1

0

Assuming you use docker and start from the position of before 1st spec file is run:

  1. Create a database dump, which you will use to restore the database to desired state
docker exec -i <container_name> /usr/bin/mongodump --username <username> --password <password> --authenticationDatabase admin --db <database_name> --out /dump
  1. Copy the dump file to mongodb container and after each spec file, do both a reset of of database and a restore using the dump file.
docker exec -i <container_name> /usr/bin/mongorestore --username <username> --password <password> --authenticationDatabase admin --db <database_name> /dump/<database_name>

Complete guide of dumping/restoring using docker containers here: https://davejansen.com/how-to-dump-restore-a-mongodb-database-from-a-docker-container/

Zaista
  • 1,272
  • 8
  • 18