Skip to content

Instantly share code, notes, and snippets.

@jaynetics
Created June 26, 2023 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaynetics/06c4270dff531a13c4f9d62b5593f442 to your computer and use it in GitHub Desktop.
Save jaynetics/06c4270dff531a13c4f9d62b5593f442 to your computer and use it in GitHub Desktop.
test in rspec that a block of code does / does not access the DB
RSpec::Matchers.define :access_db do
match do |actual|
# track db access via ActiveRecord instrumentation
sql_callback = ->(*, event) do
# ignore automatic schema queries and transactions, though
@db_event = event unless event[:sql] =~ / a\.|max_ident|SAVEPOINT/
end
ActiveSupport::Notifications.subscribed(sql_callback, 'sql.active_record') do
actual.call
end
@db_event.present?
end
failure_message_when_negated do |actual|
"expected #{actual} not to access the database, " \
"but it did by running:\n#{@db_event[:name]} - #{@db_event[:sql]}"
end
supports_block_expectations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment