0

I have a presenter:

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

and its test:

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

For some reason, this test fails with the following error:

  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)>'

Why does it fail? Why it calls the items method although I have stubbed it?

4

2 回答 2

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它非常有用,但有时不使用它会导致更简单的测试!

于 2012-12-06T18:18:25.483 回答
0

实际上我有同样的问题并以这种方式修复它:

代替:

subject.should_receive

我放:

MyPresenter.any_instance.should_receive
于 2012-12-06T16:22:51.577 回答