In my Rails app, I have a couple of controllers where I have an after_action hook that sends an email through an ActionMailer. Like so:
after_action :send_notifications, only: [:create, :update]
def send_notifications
case @record.status.downcase
when 'review', 'corrected'
RecordNotifier.received(@record).deliver_later
when 'rejected'
@rejection = Rejection.where(record_id: @record.id).last
RecordNotifier.rejected(@record, @rejection).deliver_later
when 'submitted'
@form = Form.find( @record.form_id )
RecordNotifier.submitted(@record).deliver_later
end
end
My problem is that my test suite fails randomly because sometimes a mailer will still need to finish executing after the spec has run, but since the Database gets cleaned after each test, the objects the mailer needs don't exist anymore. But I'm pretty sure thats the problem--I had one test that was failing in this way, but when I added sleep 1 before the last expect(page).to have_something statement, it passed. I could also see it in the logs--the database getting zapped before the app was ready.
Incidentally, I don't have any ActiveJob setup for the mailers, I just used deliver_later because the guides said it worked the same and if I add ActiveJob later, it will already be ready.
So how do I avoid this? How do I make sure the app is all done before the spec exits and DatabaseCleaner runs?
