Testing OAuth with Capybara/Rspec for Facebook - ruby-on-rails

I'm writing a test for Facebook integration. When I run rspec, I get the following error
Failure/Error: before { click_link "Sign in with Facebook" }
NoMethodError:
undefined method `provider' for #<Hash:0x007fbe98511798>
# ./app/models/user.rb:55:in `from_omniauth'
My OAuth mock contains
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = {
'uid' => "999999",
'provider' => "facebook",
'extra' => {
'user_hash' => {
'email' => 'test#gmail.com',
'first_name' => 'First',
'last_name' => 'Last',
'gender' => 'Male'
}
},
'credentials' => {
'token' => "token1234qwert"
}
}
The exact place it apparently breaks is
def self.from_omniauth(auth)
where("fb_provider = ? and fb_uid = ?", auth.provider, auth.uid.to_s).first_or_initialize.tap do |user|
But when I do a puts auth.to_yaml as the first line in from_omniauth(auth) it shows provider: facebook along with everything else I included in my mock auth. I'm lost at this point. Any suggestions or help would be appreciated. Thanks.

Your code should be this:
where("fb_provider = ? and fb_uid = ?", auth['provider'], auth['uid'].to_s ...
This is because auth in this instance is a Hash object and Hash objects do not respond to methods by the same name as their keys. Instead, you should just use the Hash#[] method -- as I've demonstrated -- to access the value for those keys.

Related

Why isn't Oauth setting email in tests?

# spec/support/omniauth_helper.rb
module OmniauthMacros
def mock_auth_hash
OmniAuth.config.mock_auth[:github] = {
'provider' => 'github',
'uid' => '11',
'info' => {
'email' => 'gituser#github',
'name' => 'gituser',
'image' => 'mock_user_thumbnail_url'
},
'credentials' => {
'token' => 'mock_token',
'secret' => 'mock_secret'
}
}
end
end
This returns
ActiveRecord::RecordInvalid: Validation failed: Email can't be blank.
If I move this into Test environment config it starts working. Why is this happening?

How to use aws_account_utils to create an AWS account ? Getting error : cannot load such file -- aws_account_utils

I want to use AWSAccountUtils in my project to create AWS account. I have installed gem aws_account_utils too. What more do I need to do or what is that I am missing ? In my controller I have defined following function and code is :
def create_aws_account
require 'aws_account_utils'
#account_details = []
#account_values = {}
aws_utils = AwsAccountUtils::AwsAccountUtils.new()
details = { 'fullName' => 'Devanshu Kumar',
'company' => 'ABC',
'addressLine1' => 'CP, Bund Garden Road',
'city' => 'Pune',
'state' => 'Maharastra',
'postalCode' => '411007',
'phoneNumber' => '1234567890',
'guess' => 'Test Account Dev' }
resp = aws_utils.create_account(account_name: 'My Test Account Devanshu Kumar',
account_email: 'devanshu.kumar#abc.com',
account_password: 'password',
account_details: details)
#account_values = {:account_number => data_disk.resp}
#account_details.push #account_values
render :json => { created_aws_account: account_details }
end
AWS Account Details Error Image

Create feature specs for Devise OAuth with different providers

I'm writing a Rails app with 100% test coverage. I have feature specs with Capybara for logging in with a username and password, but I don't have specs for logging in through Facebook or LinkedIn.
I didn't find an answer on the devise OmniAuth pages. Is this testable? Should I not be testing this?
I would take a look at https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview
So what I’ve ended up creating 2 helpers in my support/omniauth.rb file:
def set_omniauth(opts = {})
default = {:provider => :facebook,
:uuid => "1234",
:facebook => {
:email => "foobar#example.com",
:gender => "Male",
:first_name => "foo",
:last_name => "bar"
}
}
credentials = default.merge(opts)
provider = credentials[:provider]
user_hash = credentials[provider]
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[provider] = {
'uid' => credentials[:uuid],
"extra" => {
"user_hash" => {
"email" => user_hash[:email],
"first_name" => user_hash[:first_name],
"last_name" => user_hash[:last_name],
"gender" => user_hash[:gender]
}
}
}
end
def set_invalid_omniauth(opts = {})
credentials = { :provider => :facebook,
:invalid => :invalid_crendentials
}.merge(opts)
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[credentials[:provider]] = credentials[:invalid]
end
With this sweet setup, I can now have multiple defaults in my tests, which makes changes very clean:
background do
set_omniauth()
click_link_or_button 'Sign up with Facebook'
end
Happy Hacking

How to resolve "Insufficient Permission" error in Google Calendar API for Ruby?

I'm trying to use Google Calendar API for Ruby and this is code that I took from the google console site. But when I tried to run this code, I got this error.
......rbenv/versions/2.2.0/lib/ruby/gems/2.2.0/gems/google-api-client-0.8.6/lib/google/api_client.rb:662:in `block (2 levels) in execute!': Insufficient Permission (Google::APIClient::ClientError)
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'fileutils'
APPLICATION_NAME = 'Calendar API Quickstart'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
"calendar-api-quickstart.json")
#SCOPE = 'https://www.googleapis.com/auth/calendar.readonly'
SCOPE = 'https://www.googleapis.com/auth/calendar'
def authorize
FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
file_store = Google::APIClient::FileStore.new(CREDENTIALS_PATH)
storage = Google::APIClient::Storage.new(file_store)
auth = storage.authorize
if auth.nil? || (auth.expired? && auth.refresh_token.nil?)
app_info = Google::APIClient::ClientSecrets.load(CLIENT_SECRETS_PATH)
flow = Google::APIClient::InstalledAppFlow.new({
:client_id => app_info.client_id,
# :redirect_uri => 'http://localhost:3000/auth/google_oauth2/callback',
:client_secret => app_info.client_secret,
:scope => SCOPE})
auth = flow.authorize(storage)
puts "Credentials saved to #{CREDENTIALS_PATH}" unless auth.nil?
end
auth
end
# Initialize the API
client = Google::APIClient.new(:application_name => APPLICATION_NAME)
calendar_api = client.discovered_api('calendar', 'v3')
client.authorization = authorize
=begin
# Fetch the next 10 events for the user
results = client.execute!(
:api_method => calendar_api.events.list,
:parameters => {
:calendarId => 'primary',
:maxResults => 10,
:singleEvents => true,
:orderBy => 'startTime',
:timeMin => Time.now.iso8601 })
puts "Upcoming events:"
puts "No upcoming events found" if results.data.items.empty?
results.data.items.each do |event|
start = event.start.date || event.start.date_time
puts "- #{event.summary} (#{start})"
puts "- #{event.updated} (#{start})"
# puts "- #{event.accessRole} (#{start})"
##여기에 뭔가 생기는군
end
=end
event = {
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => {
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
},
'end' => {
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
},
'recurrence' => [
'RRULE:FREQ=DAILY;COUNT=2'
],
'attendees' => [
{'email' => 'lpage#example.com'},
{'email' => 'sbrin#example.com'},
],
'reminders' => {
'useDefault' => false,
'overrides' => [
{'method' => 'email', 'minutes' => 24 * 60},
{'method' => 'sms', 'minutes' => 10},
],
},
}
results = client.execute!(
:api_method => calendar_api.events.insert,
:parameters => {
:calendarId => 'primary'},
:body_object => event)
event = results.data
puts "Event created: #{event.htmlLink}"
I copied the functioning part from the console site here. How can I allow the permission to use Calendar application?
For the basic read-only app, I was able to run the application because I have Calendar application enabled in the console setting but don't know how to proceed the next step. Please let me know how to solve this issue :)
I was in trouble same to you. You should change two points below:
Your application name is aimed to draw quick sample data by API. It is suitable to set your own application name. The name is one you registered in Google developer console.
You should change credentials path to your own. The path you wrote is only for quick start sample.
{File.join(Dir.home, '.credentials',"calendar-api-quickstart.json"")} >>>
{File.join(Dir.home, '.credentials',"client_secret.json")}

undefined method `values_at' for nil:NilClass when I use WashOut gem

I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.

Resources