Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ActiveSupport::Notifications with rspec

Does anybody know how you can spec an active support notification? The following doesn't seem to work. It detects the default rails framework notifications but not my custom one.

it 'sends a "product.search" notification to any subscribers listening'
  ActiveSupport::Notifications.should_receive(:instrument).with("product.search", :search => search) 
  get :search, ...
end

If I change the spec to check the outcome of the subscriber's code (e.g. record count change when creating a DB record) it passes. That confirms that it is working ok. But, it seems wrong to spec what the subscriber does here, I just want to spec that the notification is being sent. Any thoughts would be appreciated.

EDIT:

Here is the controller code that I'm trying to spec:

ActiveSupport::Notifications.instrument("product.search", :search => 'test')
like image 729
tsdbrown Avatar asked Aug 24 '11 16:08

tsdbrown


2 Answers

I had the same issue and wrote the following rspec helper method below:

  def notification_payload_for(notification)
    payload = nil
    subscription = ActiveSupport::Notifications.subscribe notification do |name, start, finish, id, _payload|
      payload = _payload
    end

    yield

    ActiveSupport::Notifications.unsubscribe(subscription)

    return payload
  end

This way, I can use it as follows:

 it "should raise the my_notification_name notification" do
    payload = notification_payload_for('my_notification_name') do
      # do stuff that should raise the proper notification
    end

    # test to see that the payload has the correct info
  end
like image 124
Venkat D. Avatar answered Sep 29 '22 20:09

Venkat D.


I was unable to achieve the test using a regular :get action, something should interfere somehow and only start_processing and process_action notifications are triggered. I guess it has been disabled for performance sake.

But this successfully works:

it 'sends a "product.search" notification to any subscribers listening'
  ActiveSupport::Notifications.should_receive(:instrument).with("product.search", :search => "test")
  controller.index
end
like image 26
apneadiving Avatar answered Sep 29 '22 20:09

apneadiving