如何使用Ruby RSpec测试添加观察者的类?

时间:2013-11-05 00:52:49

标签: ruby rspec observer-pattern resque

我的任务是这样实现的:

class MyTask
    @queue = :queue_name
    include BaseTask
end

module BaseTask
    include Observable
    def perform
        add_observer(MyObserver.new)
        ...
        changed
        notify_observers
    end
end

我有一个使用include Observable方法调用performadd_observerchanged的{​​{1}} Resque任务。如何使用notify_observers测试BaseTask?我初始化了RSpec并调用了MyTask。我试过了task.performObservable.should_receive(:add_observer)MyTask.any_instance.should_receive(:add_observer),但他们没有用?

1 个答案:

答案 0 :(得分:1)

您应该能够检查MyTask实例上的消息期望。 例如,

it "is observable" do
  task = MyTask.new
  task.should_receive :add_observer
  task.should_receive :changed
  task.should_receive :notify_observers

  task.perform
end

理想情况下,我不会这样做,因为正在对被测对象进行大量的消息期望。相反,我可能会检查一些因调用perform而导致的外部状态。

修改 如果要在MyObserver上检查实例方法,可以在调用perform之前执行此类操作:

observer = mock
MyObserver.stub(:new).and_return(observer)
observer.should_receive(:some_method) #replace `some_method` with whatever instance method you want