Hi,
I’m trying to write Minitest tests for my controllers but I’m not sure what is the correct way (if there’s one) of setting up the database. I wrote a simple test including the following lines:
let(:user_repo) { UserRepository.new }
before do
user_repo.clear
user_repo.create(id: 1, email: 'user@site', name: 'Name')
end
So far so good, except that a few lines below, I’m also using a related table (understand "has a foreign key to users
"):
let(:owns_repo) { OwnsRepository.new }
before do
owns_repo.clear
owns_repo.create(car_id: 1, user_id: 1)
end
This fails on the second run with a constraint violation at repository.clear
because the values are persisted in the database between the test runs, and because I am not using an ON DELETE CASCADE
clause or allowing NULL
for my foreign key constraint (it’s part of a composite primary key, so that’s not an option).
So, starting from this small example, I’m trying to figure out what would be the best way of testing my controllers? I can see different ways:
- Clear all the relevant tables at the top of each unit test, assuming that each unit test is ran in an isolated transaction so that they won’t disturb each other (of which I have no idea whether it is done or not)
- Populate the testing database once with all needed cases, then run each unit test in an isolated transaction that is
ROLLBACK
ed automatically at the end of the test (that’s how I’m doing it for another project of mine) - Use mockups of Repository objects so that they don’t actually modify the testing database, but I have no idea whether it is possible, let alone how to do it
Can you please point me in the right direction?