Sooner of later your Ruby on Rails application will get to the level of maturity, which will require you to implement email notifications for a really complex model layer changes. And that will rise a problems of both development database pollution and code duplication between specs and mailer previews.

Let’s see how we can solve both of the problems with few simple changes to the Mailer preview layer of your Rails application.

class OurNotifierPreview < ActionMailer::Preview
  # ...
  # Wraps any of the above methods in a transaction,
  # so that the database changes are rolled back at the end of the render.
  # Which leads to links in emails being broken.
  # Due to it's nature, IDs sequences are increasing anyway.
  def self.call(...)
    preview = nil
    ActiveRecord::Base.transaction do
      preview = super(...)
      raise ActiveRecord::Rollback
    end
    preview
  end

  def welcome_new_account
    OurNotifier.something_changed(complex_model)
  end

  private
    def complex_model
      # We are changing our factories list to the smaller/different scope
      # if needed
      FactoryBot.factories.clear
      FactoryBot.definition_file_paths = ["spec/scope/factories"]
      FactoryBot.find_definitions
      # These thee lines can be omitted if we are using wider default scope
      FactoryBot.create :model, :complex
    end
end