ApprovalTests.Ruby icon indicating copy to clipboard operation
ApprovalTests.Ruby copied to clipboard

Using approvals to verify_sql

Open trevorturk opened this issue 4 years ago • 3 comments

I've had good luck with the following pattern in my apps and I'm curious if there would be any interest in wrapping this up into a new feature for the gem as we have the verify helper. No worries in any case, but I thought I'd share the pattern here for other people to consider. I find this useful for watching the SQL that complex scopes generate. It also comes in handy when working with GraphQL to ensure that common queries generate reasonable SQL. The end result is something akin to what the bullet gem does, but a bit more specialized, and with an easily readable record that prevents accidental N+1s etc.

# spec/spec_helper.rb

require "approvals/rspec"
require "./spec/support/approvals_helper"

RSpec.configure do |config|
  config.include ApprovalsHelper
  config.approvals_default_format = :txt
end
# spec/support/approvals_helper.rb

module ApprovalsHelper
  def verify_sql(&block)
    sql = []

    subscriber = ->(_name, _start, _finish, _id, payload) do
      sql << payload[:sql].split("/*").first.gsub(/\d+/, "?")
    end

    ActiveSupport::Notifications.subscribed(subscriber, "sql.active_record", &block)

    verify do
      sql.join("\n") + "\n"
    end
  end
end
# spec/models/example_spec.rb

it "is an example spec" do
   verify_sql do
     expect(
       Thing.complex_query
     ).to eq(
       expected_things
     )
   end
 end

trevorturk avatar Aug 03 '20 21:08 trevorturk

Okay, it's taken me several passes at reading this issue to even begin to understand what this is... but I'm starting to get it, and this does indeed look very cool. It'll be a while before I'm familiar enough with this codebase to be confident in adding it, but thanks for posting your solution here! :)

geeksam avatar May 28 '21 23:05 geeksam

No worries either way, and of course please feel free to close this issue... since it's not really an issue! I'd be happy to document somewhere else or provide a sample app etc, I just didn't see anywhere better to share!

trevorturk avatar May 29 '21 19:05 trevorturk

Closing this as I'm doing some house cleaning, but feel free to move do a wiki, discussion, or whatever. Thank you!

trevorturk avatar Feb 09 '22 03:02 trevorturk