对Presenter模型进行存根不起作用

时间:2012-12-06 15:28:29

标签: ruby-on-rails rspec draper

我有一位主持人:

class MyPresenter < Decorator    
  . . .

  def items
    . . .
  end

  # a method being tested which uses the above method
  def saved_items
    items.reject { |m| m.new_record? }
  end
end

及其测试:

describe MyPresenter do
  . . .

  describe "#saved_items" do
    subject { MyPresenter.new(container) }

    it "doesn't include unsaved items" do
      # I want to stub items method:
      subject.should_receive(:items).and_return([])
      subject.saved_items.should == []
    end
  end
end

由于某种原因,此测试失败并出现以下错误:

  1) MyPresenter#saved_items doesn't include unsaved items
     Failure/Error: subject.saved_items.should == []
       Double received unexpected message :items with (no args)
     # ./app/presenters/my_presenter.rb:35:in `items'
     # ./app/presenters/my_presenter.rb:42:in `saved_items'
     # ./spec/presenters/my_presenter_spec.rb:78:in `block (3 levels) in <top (required)>'

为什么会失败?为什么它会调用items方法,尽管我已经将其删除了?

2 个答案:

答案 0 :(得分:0)

实际上我遇到了同样的问题并以这种方式解决了这个问题:

而不是:

subject.should_receive

我说:

MyPresenter.any_instance.should_receive

答案 1 :(得分:0)

为什么不直接使用subject块:

 it "doesn't include unsaved items" do
   my_presenter = MyPresenter.new(container)
   my_presenter.should_receive(:items).and_return([])
   my_presenter.saved_items.should == []
 end

如果您在测试中发现重复,则可以在before块中提取对象实例化。我经常发现subject非常有用,但有时候不使用它会导致更简单的测试!