instance method assert_event_reported

Ruby on Rails 8.1.2

Since v8.1.2

Signature

assert_event_reported(name, payload: nil, tags: {}, &block)

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

Parameters

name req
payload key = nil
tags key = {}
block block
Source
# File activesupport/lib/active_support/testing/event_reporter_assertions.rb, line 142
      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.inspect}\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

Defined in activesupport/lib/active_support/testing/event_reporter_assertions.rb line 142 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActiveSupport::Testing::EventReporterAssertions

Type at least 2 characters to search.

↑↓ navigate · open · esc close