Advertisement
Guest User

Untitled

a guest
Jul 3rd, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. # Allows for assertions regarding number of queries executed.
  2. #
  3. # Usage:
  4. # it "eager loads `#manager` association" do
  5. # expect do
  6. # employee = Employee.with_manager.find(employee_id)
  7. # employee.manager
  8. # end.to satisfy_query_limit(1)
  9. # end
  10. RSpec::Matchers.define :satisfy_query_limit do |expected|
  11. match do |block|
  12. count_queries(&block) <= expected
  13. end
  14.  
  15. failure_message_for_should do |actual|
  16. "Expected to execute no more than #{expected} SQL queries, got #{@query_count}"
  17. end
  18.  
  19. failure_message_for_should_not do |actual|
  20. "Expected to execute more than #{expected} SQL queries, got #{@query_count}"
  21. end
  22.  
  23. def count_queries
  24. @query_count = 0
  25. filter_list = %w[CACHE SCHEMA]
  26. # Rails 3.2 introduces ActiveSupport::Notifications::subscribed for temporary
  27. # subscribers. Use that for 3.2+
  28. query_counter = ->(name, started, finished, unique_id, payload) do
  29. @query_count += 1 unless payload[:name].in?(filter_list)
  30. end
  31. subscriber = ActiveSupport::Notifications.subscribe("sql.active_record", query_counter)
  32. yield
  33. ActiveSupport::Notifications.unsubscribe(subscriber)
  34. @query_count
  35. end
  36. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement