2012-07-19 31 views
0

在我SubscriptionsController我:如何在rails和rspec中模擬鏈接關聯?

# DELETE /subscription # {{{ 
    def destroy 
    @subscription = current_user.subscriptions.find params[:id] 
    @subscription.cancel! 
    redirect_to subscriptions_path, :notice => "Abonnement beendet." 
    end# }}} 

什麼是模擬出在我的控制器,規格current_user.subscriptions.find params[:id]正確的方法是什麼?

目前我正在嘗試在我之前的塊。

double(Subscription) 
    controller.current_user.stub!(:subscriptions).and_return(Subscription) 
    Subscription.stub!(:find).and_return(subscription) 

但這看起來不像預期的那樣工作,因爲我的RSpec-Expectations不起作用。

it "updates the status to canceled" do 
    sub = Subscription.stub!(:find).and_return(subscription) 
    sub.stub!(:cancel!) 
    sub.should_receive :cancel! 
    delete :destroy, :id => 1 
end 

這一塊總是失敗的因爲...期望should_receive不滿足:

1) SubscriptionsController DELETE /subscription/:id updates the status to canceled 
    Failure/Error: sub.should_receive :cancel! 
    (#<Proc:[email protected]/Users/nilsriedemann/.rvm/gems/[email protected]/gems/rspec-mocks-2.6.0/lib/rspec/mocks/message_expectation.rb:63 (lambda)>).cancel!(any args) 
    expected: 1 time 
    received: 0 times 
    # ./spec/controllers/subscriptions_controller_spec.rb:38:in 
    # `block (3 levels) in <top (required)>' 
    # ' 

此外,如果有人滴不錯鏈接到有關磕碰透徹的文章,在評論嘲諷,我會很高興的離譜。仍然(顯然)沒有得到這一點。

回答

4

您正在設置訂閱上的should_receive,而不是find將返回的對象。

喜歡的東西

Subscription.stub!(:find).and_return(subscription) 
subscription.should_receive :cancel! 

是你所追求的。

您可能也有興趣stub_chain

some_user.stub_chain(:subscriptions, :find => some_result) 

套東西,這樣

some_user.subscriptions.find 

回報some_result

+0

這對我來說非常合適,所以謝謝!我也嘗試一下存根鏈的幾個屬性,但它不起作用。你必須爲每個屬性聲明一個單獨的'#stub_chain'。這對某些人來說可能是顯而易見的,但它讓我絆了一會兒,所以我想我會分享。 – 2013-09-06 15:30:43

1

有幾種方法可以做到這一點。如果你想要一個簡單的解決方案,你可以使用stub_chain並把它傳遞儘可能多的方法,只要你想:

let(:subscription) { mock(:subscription) } 
current_user.stub_chain(:subscriptions, :find) { subscription } 

而另一個將是不能直接使用的活動記錄,並且對用戶模型查找方法:

let(:subscription) { mock(:subscription) } 
current_user.stub(:find_subscription) { subscription } 

這真的是一個意見的問題,歸結爲任何你感到最舒服的。我個人會選擇一個。