In my app I have a model that has after_create and after_destroy methods that create a directory and then destroy it respectively on the filesystem.
I’ve noticed in my RSpec request specs that the model records get created find (thus the directories get created), but I’m assuming the records are just deleted after each spec rather than destroyed, thus the directories hang around instead of being deleted. Either that or perhaps RSpec just rolls back the database transaction around the whole spec?
My question is, how can I make RSpec safely destroy these records so that the filesystem stays in sync?
I’ve tried:
after(:each) do
Entity.destroy_all
end
and that works, but I’m not sure it’s the best way.
Perhaps I could be doing it better in my model itself so that if I detect a transaction rollback I can delete the directory then too? I’ve never heard of this functionality though bar perhaps in a begin rescue ensure block.
Any tips?
Turns out that you can turn off transactions for certain spec’s like ones that need to completely add the record and run certain after callbacks. I also modified by after_create to an after_commit(:on => :create) (not 100% sure on the syntax, just taking that from memory) to add and remove filesystem elements because that’s the safest way to ensure that the record exists in the database before making the filesystem changes.