How would you test observers with rSpec in a Ruby on Rails application?

前端 未结 4 558
萌比男神i
萌比男神i 2020-12-23 09:50

Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?

4条回答
  •  攒了一身酷
    2020-12-23 10:23

    If you want to test that the observer observes the correct model and receives the notification as expected, here is an example using RR.

    your_model.rb:

    class YourModel < ActiveRecord::Base
        ...
    end
    

    your_model_observer.rb:

    class YourModelObserver < ActiveRecord::Observer
        def after_create
            ...
        end
    
        def custom_notification
            ...
        end
    end
    

    your_model_observer_spec.rb:

    before do
        @observer = YourModelObserver.instance
        @model = YourModel.new
    end
    
    it "acts on the after_create notification"
        mock(@observer).after_create(@model)
        @model.save!
    end
    
    it "acts on the custom notification"
        mock(@observer).custom_notification(@model)
        @model.send(:notify, :custom_notification)
    end
    

提交回复
热议问题