Skip to content

Commit

Permalink
Add Example use cases with verify_sql in README
Browse files Browse the repository at this point in the history
  • Loading branch information
trevorturk authored and geeksam committed Feb 4, 2025
1 parent 64f1974 commit 8881050
Showing 1 changed file with 47 additions and 1 deletion.
48 changes: 47 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)<!-- endToc -->
* [RSpec executable](#rspec-executable)
* [Example use cases](#example-use-cases)
* [Verifying complex SQL in Rails](#verifying-complex-sql-in-rails)<!-- endToc -->

Approvals are based on the idea of the *_golden master_*.

Expand Down Expand Up @@ -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

0 comments on commit 8881050

Please sign in to comment.