2010-11-17 107 views
0

我試圖測試一下控制器在Rails 2.3.10上的操作,它連接到Google以檢索聯繫人。我正在使用Rspec和Mocha進行測試。由於這是一次單元測試,因此我想將實際的電話撥到Google上。我想驗證用正確的參數調用authsub_url方法。對方法進行保留會導致期望失敗。RSpec谷歌聯繫人連接

任何意見,將不勝感激。

謝謝!

我的方法,設置了客戶端谷歌低於:

def setup_client 
    @client = GData::Client::DocList.new(:authsub_scope => CONTACTS_SCOPE, :source => 'google-DocListManager-v1.1', :version => '3.0')  

    if params[:token].nil? && session[:google_token].nil? 
     @authsub_link = @client.authsub_url(import_method_gmail_url, false, true) 
     render :action => :index, :layout => "empty" 
    elsif params[:token] && session[:google_token].nil? 
     @client.authsub_token = params[:token] 
     session[:google_token] = @client.auth_handler.upgrade 
    end 

    @client.authsub_token = session[:google_token] if session[:google_token] 
    end 

這裏是我的測試:

describe "setup_client" do 
    it "has a authsub_link if there is no token parameter and the google token is not present in the session" do 
     GData::Client::DocList.any_instance.stubs(:authsub_url).returns("http://test.google.com/contacts") 
     user = Factory(:subscriber_user) 
     profile = Factory(:profile, :user => user) 
     login_as user 

     controller.instance_variable_get(:@client).expects(:authsub_url).with(import_method_gmail_url, false, true).once 

     get :index 

     assigns(:authsub_link).should == "http://test.google.com/contacts" 
    end 
    end 

回答

0

我會建議FakeWeb。它允許你僞造Web請求。簡單定義你要調用的URL並準備響應。讓你的生活變得非常簡單。

0

看起來你是在兩個地方磕碰出DocList#authsub_url方法: -

第一支腳是對DocList任何實例,並返回一個網址: -

GData::Client::DocList.any_instance.stubs(:authsub_url).returns("http://test.google.com/contacts") 

第二支腳是的DocList實際的實例,但這個返回nil,因爲沒有沒有returns條款: -

controller.instance_variable_get(:@client).expects(:authsub_url).with(import_method_gmail_url, false, true).once 

我想你可以實現你將它們組合這樣的東西想要的東西: -

controller.instance_variable_get(:@client).expects(:authsub_url).with(import_method_gmail_url, false, true).returns("http://test.google.com/contacts") 

注意once是默認所以不需要,除非你想強調的是,該方法只能被調用一次。