如何与twitter gem和capybara进行集成测试?

时间:2011-11-28 21:00:21

标签: ruby twitter integration-testing capybara omniauth

我正在编写一个使用Devise + OmniAuth登录的示例应用程序和twitter gem来获取用户名。我想添加一些集成测试,但我不知道如何处理twitter gem。

这是我的用户模型(这是找到大部分逻辑的地方):

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 gem的build_twitter方法。任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:2)

我的第一个注意事项是,你可以在没有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”还是“Josh Crews”,具体取决于您要查找的内容