2012-12-06 47 views
0

我有一個主持人:打樁一個演示模型不能正常工作

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方法,儘管我已將它存根?

+0

我想我明白了,你有一個代表物品權的方法嗎?你的容器是雙重的? – apneadiving

+0

容器是雙重的,是的。不確定委託方法,'items'實質上是在ItemPresenter中包裝容器的items集合。 –

回答

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是非常有用的,但有時更簡單的測試可能會導致不使用它!