From 61669d1e9a0fe2ef7256fc953905b617627f24ff Mon Sep 17 00:00:00 2001 From: Trevor Turk Date: Mon, 14 Nov 2022 11:42:07 -0600 Subject: [PATCH] Add Example use cases with verify_sql in README --- README.md | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c47439..6cb9952 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,9 @@ * [Exclude dynamically changed values from json](#exclude-dynamically-changed-values-from-json) * [Approving a spec](#approving-a-spec) * [Expensive computations](#expensive-computations) - * [RSpec executable](#rspec-executable) + * [RSpec executable](#rspec-executable) + * [Example use cases](#example-use-cases) + * [Verifying complex SQL in Rails](#verifying-complex-sql-in-rails) Approvals are based on the idea of the *_golden master_*. @@ -284,4 +286,48 @@ verify do end ``` +## Example use cases + +### Verifying complex SQL in Rails + +If you're using Rails and want to avoid accidentally introducing N+1 database queries, you can define a `verify_sql` helper like so: + +```ruby +# spec/spec_helper.rb + +require "./spec/support/approvals_helper" + +RSpec.configure do |config| + config.include ApprovalsHelper +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 :format => :txt 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 +``` + +This `verify_sql` can be useful in model or integration tests; anywhere you're worried about the SQL being generated by complex queries, API endpoints, GraphQL fields, etc. + Copyright (c) 2011 Katrina Owen, released under the MIT license