Created
June 26, 2023 19:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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