2009-12-08 42 views
2

我是新的tdd和stubbing。當我存在一個方法,我認爲該方法中的任何代碼不會被執行?我試圖僞造引發異常的方法,但我的測試結果表明該方法中的代碼正在執行而不是被繞過。摩卡咖啡是否運行存根(Rails)中的代碼?

任何人都可以幫忙解釋爲什麼?

我的磕碰是

@logged_in_user.subscription.stubs(:stop_auto_renew).raises(:RuntimeError) 

,並在上下文中

test "canceling subscription should handle exception raised by spreedly" do 
    login_larry_active 
    @logged_in_user.subscription.stubs(:stop_auto_renew).raises(:RuntimeError) 
    delete :destroy, {:user_id => @logged_in_user.id} 
    assert flash[:notice] 
    assert_redirected_to :controller => :dashboard, :action => :welcome 
end 

這是在我的模型我嘗試存根方法。 Spreedly ::訂閱者通常通過網絡獲取內容。

class Subscription < ActiveRecord::Base 
    protected 
    def stop_auto_renew 
     Spreedly::Subscriber.find(self.user.id).stop_auto_renew() 
    end 
end 

-

class SubscriptionsController < ApplicationController  
    def destroy 
     user = User.find(params[:user_id]) 
     if user 
      begin 
       user.subscription.stop_auto_renew 
      rescue RuntimeError 
       #log something and email admin 
       ldb("Spreedly cant process stop_auto_renew for user id: #{user.id}") 
       #email admin 
      end 
      flash[:notice] = "You have successfully cancelled your subscription and will take effect at the end of your current billing month" 
     end  
     redirect_to :controller => :dashboard, :action => :welcome 
    end 
end 

和測試誤差

4) Error: 
test_canceling_subscription_should_handle_exception_raised_by_spreedly(SubscriptionsControllerTest): 
NoMethodError: You have a nil object when you didn't expect it! 
The error occurred while evaluating nil.stop_auto_renew 
    app/models/subscription.rb:18:in `stop_auto_renew' 
    app/controllers/subscriptions_controller.rb:31:in `destroy' 
    /test/functional/subscriptions_controller_test.rb:42:in `test_canceling_subscription_should_handle_exception_raised_by_spreedly' 

回答

3

我可能是錯的,但我的猜測是,你有存根的方法:stop_auto_renew對象@logged_in_user.subscription上(我假設用戶有訂閱嗎?),但實際上是在您的控制器中的User.find(params[:user_id])創建的不同實例上進行的。

也許試試Subscription.any_instance.stubs(:stop_auto_renew)...應該保留訂閱的所有實例。

+0

你的權利。我是新來的摩卡,儘管它在文檔中面對我,但錯過了重要的any_instance部分。非常感謝您的幫助! – robodisco 2009-12-10 14:05:46

+0

沒問題,只是很高興幫助!跟上TDD,它確實還清了大聲笑。 – tsdbrown 2009-12-10 14:13:36