2012-02-25 70 views
0

當試圖取消關注的用戶不存在時,我會拋出一個異常來設置Flash錯誤消息,並將用戶重定向回到他們所在的頁面。如何使用RSpec在已存在的控制器方法上存根方法?

所有對twitter gem的訪問都由TwitterManager類處理,它是一個常規的ruby類,它擴展了ActiveModel :: Naming來啓用mock_model。

現在我有一個真正的困難時間搞清楚這應該如何測試。下面的代碼工作,但感覺非常錯誤。唯一可以將twitter.unfollow方法存根的方法是使用controller.send(:twitter).stub(:unfollow).and_raise(Twitter :: Error :: NotFound.new(「」,{}))

我嘗試使用TwitterManager.any_instance.stub(:unfollow),但那顯然沒有做我認爲會做的事情。

我該如何做得更好?我完全誤解了什麼?

規格

describe TwitterController do 

    before(:each) do 
    controller.stub(:twitter).and_return(mock_model("TwitterManager", unfollow: true, follow: true)) 
    end 

    it "unfollows a user when given a nickname" do 
    @request.env['HTTP_REFERER'] = '/followers' 
    post 'unfollow', id: "existing_user" 
    response.should redirect_to followers_path 
    end 

    describe "POST 'unfollow'" do 
    it "does not unfollow a user that does not exist" do 
     controller.send(:twitter).stub(:unfollow).and_raise(Twitter::Error::NotFound.new("", {})) 
     @request.env['HTTP_REFERER'] = '/followers' 
     post 'unfollow', id: "non_existing_user" 

     flash[:error].should_not be_nil 
     flash[:error].should have_content("not found, could not unfollow") 
     response.should redirect_to followers_path 
    end 
    end 

控制器

def unfollow 
    begin 
     twitter.unfollow(params[:id]) 
     respond_to do |format| 
     format.html { redirect_to :back, notice: "Stopped following #{params[:id]}" } 
     end 
    rescue Twitter::Error::NotFound 
     redirect_to :back, :flash => { error: "User #{params[:id]} not found, could not unfollow user" } 
    end 
    end 

[更多代碼]

private 
    def twitter 
    twitter_service ||= TwitterFollower.new(current_user) 
    end 

Rspec的2.8.0 的Rails 3.2.0

回答

1

你可以清理一個一點一點地節省模擬TwitterManager作爲before塊實例變量,直接在對象上磕碰:

describe TwitterController do 

    before(:each) do 
    @twitter = mock_model("TwitterManager", unfollow: true, follow: true) 
    controller.stub(:twitter).and_return(@twitter) 
    end 

    # ... 

    describe "POST 'unfollow'" do 
    it "does not unfollow a user that does not exist" do 
     @twitter.stub(:unfollow).and_raise(Twitter::Error::NotFound.new("", {})) 
     # ... 
    end 
    end 
end 

但我不會說,你正在做的事情是「非常錯誤的」 :-)

相關問題