My R package modifies data in a remote DB and I'd like to write some tests with testthat.
I am aware that I could mock the DB but I'd rather simply use of one our dev DB.
How can I make a db connection available to all tests that need it, while making sure any connection created is destroyed? It seems obvious that connecting should happen in a setup and disconnecting in a teardown, but I haven't managed.
I have tried to put the following code in tests/testthat.R or in a helper file tests/testthat/helper-_, to no avail.
setup({
# db_connect is just a basic wrapper around RMariaDB::dbConnect with logging
db_con <- db_connect(conf$database, loglevel = "none")
})
teardown({
# db_connect is just a basic wrapper around DBI::dbDisconnect with logging
db_disconnect(db_con = db_con, loglevel = "none")
})
My initial tests are:
tests
├── testthat
│ ├── helper-_.R
│ ├── test-connect.R
│ └── test-questions.R
└── testthat.R
After the first file (where all tests pass), I get Error in DBI::dbDisconnect(db_con) : object 'db_con' not found which indicates the teardown is happening but the db_con is not found.
After that, all tests requiring db_con fail with object 'db_con' not found.
Do I have to create a helper file for each file where db_con is needed? Or do I have to explicitly source a common helper file?
Is there a way I can set up the connection once somewhere and have it available to all tests and destroyed at the end?