Skip to content

Instantly share code, notes, and snippets.

@invisiblefunnel
Last active July 30, 2020 19:25
Show Gist options
  • Save invisiblefunnel/38cc8fde326fcdc75b578abec3faad4a to your computer and use it in GitHub Desktop.
Save invisiblefunnel/38cc8fde326fcdc75b578abec3faad4a to your computer and use it in GitHub Desktop.
module SQLApprovals
def verify_sql(name:, &block)
# List to store executed queries
queries = []
# An event listener to record the normalized queries
subscriber = ->(_name, _start, _finish, _id, payload) do
# You'll likely need to filter unrelated queries,
# this is left as an exercise to the reader
queries << PgQuery.normalize(payload[:sql])
end
# Subscribe the listener to Active Record SQL events and execute the given block.
ActiveSupport::Notifications.subscribed(subscriber, "sql.active_record", &block)
# Build a text representation of the executed queries
result = queries.join("\n") + "\n"
# Assert on the normalized results as a block of text
Approvals.verify(result, name: name, format: :txt)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment