Created
March 28, 2025 13:08
-
-
Save amkisko/0f3bd9a5740cbe78d11205880a9c96dd to your computer and use it in GitHub Desktop.
ActiveRecord SQL logger helper, shows only INSERT/UPDATE/DELETE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
it "does something" do | |
log_sql do | |
request | |
expect(create_call).to_not raise_exception | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def log_sql | |
subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |event| | |
payload = event.payload[:sql] | |
next if payload.match?(/^(SELECT|SET|SHOW|BEGIN|COMMIT|ROLLBACK|RELEASE|SAVEPOINT)/) | |
event.payload[:type_casted_binds].each_with_index do |bind, index| | |
payload = payload.gsub("$#{index + 1}", "'#{bind}'") | |
end | |
puts payload | |
end | |
yield | |
ActiveSupport::Notifications.unsubscribe(subscriber) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment