2011-11-28 116 views
1

我正在編寫一個使用Devise + OmniAuth登錄的示例應用程序,並使用twitter gem來獲取用戶名。我想添加一些集成測試,但我不知道如何處理twitter gem。我如何使用twitter gem和capybara進行集成測試?

這裏是我的用戶模型(這是大多數的邏輯被發現):

def build_authentication(omniauth) 
    # If the provider is twitter, get additional information      
    # to build a user profile.             
    if omniauth['provider'] == 'twitter'   
    self.build_twitter(omniauth) 
    end 

    # now put the authentication in the database         
    authentications.build(:provider => omniauth['provider'], 
         :uid => omniauth['uid'], 
         :token => omniauth['credentials']['token'], 
         :secret => omniauth['credentials']['secret']) 
end 
def build_twitter(omniauth) 
    Twitter.configure do |config| 
    config.consumer_key = TWITTER_KEY 
    config.consumer_secret = TWITTER_SECRET 
    config.oauth_token = omniauth['credentials']['token'] 
    config.oauth_token_secret = omniauth['credentials']['secret'] 
    end 
    client = Twitter::Client.new 
    self.name = client.current_user.name 
end 

我已經添加下面我spec_helper.rb讓我通過集成測試的登錄部分:

OmniAuth.config.test_mode = true 
OmniAuth.config.mock_auth[:twitter] = { 
    'provider' => 'twitter', 
    'uid' => '12345', 
    'credentials' => { 
    'token' => '12345', 
    'secret' => '54321' 
    } 
} 

但我無法弄清楚如何測試它使用Twitter的寶石build_twitter方法。任何幫助將不勝感激。

謝謝!

回答

2

我的第一個說明是,你可以得到他們的twitter名稱沒有twitter的寶石。我已將字段(twitter_handle,real_name)重命名爲特定字段。

self.twitter_handle ||= omniauth['user_info']['nickname'] 
self.real_name = omniauth['user_info']['name'] 

然後,您可以使用omniauth測試模式對其進行測試。某處掛鉤或rspec的助手

OmniAuth.config.test_mode = true 

    # the symbol passed to mock_auth is the same as the name of the provider set up in the initializer 
    OmniAuth.config.mock_auth[:twitter] = { 
    "provider"=>"twitter", 
    "uid"=>"1694349", 
    "credentials"=>{ 
     "token"=>"165349-aRlUJ7TeIb4Ak57oqycgwihqobrzQ0k5EI7", 
     "secret"=>"SNZT7S70xZIhANfZzgHUEpZMPSsGEHw" 
    }, 
    "user_info"=>{"nickname"=>"joshcrews", "name"=>"Josh Crews", "location"=>"Nashville, TN", "image"=>"http://a3.twimg.com/profile_images/1076036384/josh_profile_franklin_normal.jpg", "description"=>"Christian, Nashville web developer, Ruby", "urls"=>{"Website"=>"http://www.joshcrews.com", "Twitter"=>"http://twitter.com/joshcrews"}} 
    } 

測試之前,你的黃瓜,只是斷言/應該就是你的用戶名,現在是不是「joshcrews」或取決於你在找什麼

+0

感謝「喬希克魯斯」答案。我知道我使用twitter gem的效率並不高,而且我可以從omniauth hash中獲得名稱,但這是一個我實際上想要設置omniauth和twitter gem的示例。 – spinlock

+0

很酷。那麼我已經對Twitter的寶石進行了測試,但非常非常有限。我使用摩卡並有'Twitter :: Client.any_instance.expects(:update)'來確保在集成測試期間調用該方法。 –

+0

值得添加另一個gem/syntax嗎?摩卡看起來很有趣,但我想回到編寫代碼而不是學習新的測試框架:) – spinlock

相關問題