Skip to Content Skip to Search

module ActiveSupport::Testing::EventReporterAssertions

Provides test helpers for asserting on ActiveSupport::EventReporter events.

Public instance methods

Asserts that the block causes an event with the given name to be reported to Rails.event.

Passes if the evaluated code in the yielded block reports a matching event.

assert_event_reported("user.created") do
  Rails.event.notify("user.created", { id: 123 })
end

To test further details about the reported event, you can specify payload and tag matchers.

assert_event_reported("user.created",
  payload: { id: 123, name: "John Doe" },
  tags: { request_id: /[0-9]+/ }
) do
  Rails.event.tagged(request_id: "123") do
    Rails.event.notify("user.created", { id: 123, name: "John Doe" })
  end
end

The matchers support partial matching - only the specified keys need to match.

assert_event_reported("user.created", payload: { id: 123 }) do
  Rails.event.notify("user.created", { id: 123, name: "John Doe" })
end
Source code GitHub
# File activesupport/lib/active_support/testing/event_reporter_assertions.rb, line 143
def assert_event_reported(name, payload: nil, tags: {}, &block)
  events = EventCollector.record(&block)

  if events.empty?
    flunk("Expected an event to be reported, but there were no events reported.")
  elsif (event = events.find { |event| event.matches?(name, payload, tags) })
    assert(true)
    event.event_data
  else
    message = "Expected an event to be reported matching:\n  " \
      "name: #{name}\n  " \
      "payload: #{payload.inspect}\n  " \
      "tags: #{tags.inspect}\n" \
      "but none of the #{events.size} reported events matched:\n  " \
      "#{events.map(&:inspect).join("\n  ")}"
    flunk(message)
  end
end

Asserts that the block does not cause an event to be reported to Rails.event.

If no name is provided, passes if evaluated code in the yielded block reports no events.

assert_no_event_reported do
  service_that_does_not_report_events.perform
end

If a name is provided, passes if evaluated code in the yielded block reports no events with that name.

assert_no_event_reported("user.created") do
  service_that_does_not_report_events.perform
end
Source code GitHub
# File activesupport/lib/active_support/testing/event_reporter_assertions.rb, line 102
def assert_no_event_reported(name = nil, payload: {}, tags: {}, &block)
  events = EventCollector.record(&block)

  if name.nil?
    assert_predicate(events, :empty?)
  else
    matching_event = events.find { |event| event.matches?(name, payload, tags) }
    if matching_event
      message = "Expected no '#{name}' event to be reported, but found:\n  " \
        "#{matching_event.inspect}"
      flunk(message)
    end
    assert(true)
  end
end

Definition files