Skip to content

Using approvals to verify_sql #91

Open
@trevorturk

Description

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

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions