how can I do integration testing with the twitter gem and capybara?
-
25-10-2019 - |
Question
I'm writing an example app using Devise + OmniAuth for logging in and the twitter gem to get the users name. I'd like to add a few integration tests but I don't know what to do with the twitter gem.
Here's my user model (which is where most of the logic is found):
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
I've added the following to my spec_helper.rb so that I pass the login part of the integration test:
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:twitter] = {
'provider' => 'twitter',
'uid' => '12345',
'credentials' => {
'token' => '12345',
'secret' => '54321'
}
}
But I can't figure out how to test the build_twitter
method which uses the twitter gem. Any help would be greatly appreciated.
Thanks!
Solution
My first note is that you can get their twitter name without the twitter gem. I've renamed the fields (twitter_handle, real_name) to be specific.
self.twitter_handle ||= omniauth['user_info']['nickname']
self.real_name = omniauth['user_info']['name']
You can then test this with omniauth test mode. Somewhere in your Cucumber before hooks or rspec helpers
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"}}
}
To test, just assert/should that your user's name is now either "joshcrews" or "Josh Crews" depending on what you are looking for