Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Example use cases with verify_sql in README #120

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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