Skip to content

Instantly share code, notes, and snippets.

@pch
Last active October 29, 2022 21:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pch/7943475 to your computer and use it in GitHub Desktop.
Save pch/7943475 to your computer and use it in GitHub Desktop.
assert_queries - rails 4
# Assertion for checking the number of queries executed within the &block
def assert_queries(num = 1, &block)
queries = []
callback = lambda { |name, start, finish, id, payload|
queries << payload[:sql] if payload[:sql] =~ /^SELECT|UPDATE|INSERT/
}
ActiveSupport::Notifications.subscribed(callback, "sql.active_record", &block)
ensure
assert_equal num, queries.size, "#{queries.size} instead of #{num} queries were executed.#{queries.size == 0 ? '' : "\nQueries:\n#{queries.join("\n")}"}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment