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

前端 未结 4 565
萌比男神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:37

    Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use mock objects, should_receive and friends, and invoke methods on the observer directly

    Given the following model and observer:

    class Person < ActiveRecord::Base
      def set_status( new_status )
        # do whatever
      end
    end
    
    class PersonObserver < ActiveRecord::Observer
      def after_save(person)
        person.set_status("aha!")
      end
    end
    

    I would write a spec like this (I ran it, and it passes)

    describe PersonObserver do
      before :each do
        @person = stub_model(Person)
        @observer = PersonObserver.instance
      end
    
      it "should invoke after_save on the observed object" do
        @person.should_receive(:set_status).with("aha!")
        @observer.after_save(@person)
      end
    end
    

提交回复
热议问题