Skip to content

Commit

Permalink
Specs added
Browse files Browse the repository at this point in the history
  • Loading branch information
Pbasnal committed Jul 14, 2014
1 parent e4dbba3 commit c472969
Show file tree
Hide file tree
Showing 18 changed files with 2,118 additions and 81 deletions.
3 changes: 3 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,9 @@ group :development, :test do
gem 'database_cleaner'
# Use to track how much code has been tested
gem 'simplecov', '~> 0.7.1'
end

group :test do
# Webmock to stub http requests
gem 'webmock'
# VCR to record the responses from web and replay them when needed
Expand Down
31 changes: 21 additions & 10 deletions app/controllers/spreadsheets_controller.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class SpreadsheetsController < ApplicationController
include GoogleSpreadsheets
require 'google'
include Google::Spreadsheets

def index
@spreadsheets = Spreadsheet.all.to_a
Expand All @@ -15,18 +16,23 @@ def new

if spreadsheet.save
# Spreadsheets from google
@spreadsheets = get_spreadsheets(spreadsheet)
@spreadsheets = list(spreadsheet)
@token = spreadsheet.access_token
else
# Handle if data does not get saved
@msg = 'Getting same access token. Try deleting '
end
end

def edit
token = spreadsheet_params['token']
spreadsheet = Spreadsheet.where(access_token: token)[0]
spreadsheet.add_spreadsheet_credentials(spreadsheet_params)
spreadsheet.save

if spreadsheet.add_spreadsheet_credentials(spreadsheet_params)
spreadsheet.save
else
@error = 'Already Present'
end

@spreadsheets = Spreadsheet.all.to_a

Expand All @@ -35,8 +41,9 @@ def edit

def update
spreadsheet = Spreadsheet.find(params['id'])
@worksheet = get_worksheets(spreadsheet)
@worksheet = worksheets(spreadsheet)
User.add_users_from_worksheet(@worksheet)

redirect_to users_path
end

Expand All @@ -45,15 +52,19 @@ def destroy
redirect_to spreadsheets_path
end

def spreadsheet_params
params.permit(:title, :id, :token)
end

def failure
if params['message'].match('access_denied')
@msg = "Account integration Failed. User Refused to grant permissions"
@msg = 'Account integration Failed. User Refused to grant permissions'
end
@spreadsheets = Spreadsheet.all.to_a
render action: 'index'
end

#################################
private
#################################

def spreadsheet_params
params.permit(:title, :id, :token)
end
end
2 changes: 0 additions & 2 deletions app/helpers/callbacks_helper.rb

This file was deleted.

3 changes: 1 addition & 2 deletions app/models/spreadsheet.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class Spreadsheet
field :expires_at, type: Time
field :access_token, type: String

validates :access_token, uniqueness: true
validates :access_token, presence: true, uniqueness: true

def add_tokens(tokens = {})
self['access_token'] = tokens.fetch('token')
Expand All @@ -16,7 +16,6 @@ def add_tokens(tokens = {})
end

def add_spreadsheet_credentials(credentials = {})
#binding.pry
self['spreadsheet_id'] = credentials['id']
self['spreadsheet_title'] = credentials['title']
end
Expand Down
10 changes: 7 additions & 3 deletions app/views/spreadsheets/index.html.haml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
= @msg if @msg
%h4
=link_to 'Add New Spreadsheet', 'auth/google/'
=link_to 'Add New Spreadsheet', '/auth/google/'

%table.table.table-striped
%tr.info
Expand All @@ -19,10 +19,14 @@
%td
= i = i + 1
%td
- if ss['spreadsheet_title']
-if ss['spreadsheet_title']
=ss['spreadsheet_title']
-else
=link_to 'Spreadsheet not initialised', new_spreadsheet_path(access_token: ss['access_token'])
=link_to 'Get Spreadsheet', new_spreadsheet_path(access_token: ss['access_token'])
-if @error
(
=@error
)
%td
=link_to 'Delete', spreadsheet_path(ss), method: :delete
-if ss['spreadsheet_title']
Expand Down
13 changes: 7 additions & 6 deletions app/views/spreadsheets/new.html.haml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
%br
-count = @spreadsheets.count
=count
-count.times do |i|
=link_to @spreadsheets[i]['title'], edit_spreadsheet_path(@spreadsheets[i]['id'], title: @spreadsheets[i]['title'], token: @token) if @spreadsheets[i]['mimeType'].include?('spreadsheet')
%br
-if @msg
=@msg
-else
-count = @spreadsheets.count
-count.times do |i|
=link_to @spreadsheets[i]['title'], edit_spreadsheet_path(@spreadsheets[i]['id'], title: @spreadsheets[i]['title'], token: @token) if @spreadsheets[i]['mimeType'].include?('spreadsheet')
%br
2 changes: 1 addition & 1 deletion config/mongoid.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ development:

# Raise an error when performing a #find and the document is not found.
# (default: true)
# raise_not_found_error: true
raise_not_found_error: false

# Raise an error when defining a scope with the same name as an
# existing method. (default: false)
Expand Down
44 changes: 44 additions & 0 deletions lib/google.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
module Google
module Spreadsheets
def list(spreadsheet)
if Time.now > spreadsheet['expires_at']
spreadsheet = refresh_token spreadsheet
end

client = Google::APIClient.new
client.authorization.access_token = spreadsheet.access_token
drive = client.discovered_api('drive', 'v2')

wks = client.execute(
api_method: drive.files.list,
parameters: {},
headers: {'Content-Type' => 'application/json'}
)
(JSON.parse(wks.data.to_json))['items']
end

def worksheets(spreadsheet, index = 0)
if DateTime.now.utc > spreadsheet['expires_at']
spreadsheet = refresh_token spreadsheet
end

session = GoogleDrive.login_with_oauth(spreadsheet['access_token'])
session.spreadsheet_by_key(spreadsheet['spreadsheet_id']).worksheets[index]
end

def refresh_token(spreadsheet)
client = Google::APIClient.new
client.authorization.client_id = ENV['GOOGLE_ID']
client.authorization.client_secret = ENV['GOOGLE_KEY']
client.authorization.grant_type = 'refresh_token'
client.authorization.refresh_token = spreadsheet['refresh_token']
re = client.authorization.fetch_access_token!

spreadsheet['access_token'] = re['access_token']
spreadsheet['expires_at'] = (Time.now + re['expires_in'].second)
spreadsheet.save

spreadsheet
end
end
end
46 changes: 0 additions & 46 deletions lib/google_spreadsheets.rb

This file was deleted.

122 changes: 112 additions & 10 deletions spec/controllers/spreadsheets_controller_spec.rb
Original file line number Diff line number Diff line change
@@ -1,29 +1,131 @@
require 'rails_helper'
require 'webmock/rspec'
require 'vcr'

RSpec.describe SpreadsheetsController, :type => :controller do
google_auth_response = File.new('spec/controllers/google_auth_response.json')

context 'GET User Permission' do
context 'User accepts' do
it 'redirects to new ' do
VCR.use_cassette 'controllers/api-permissions' do
data = {
name: 'google',
scope: 'userinfo.profile,userinfo.email,drive,https://spreadsheets.google.com/feeds',
prompt: 'consent',
access_type: 'offline',
redirect_uri: 'http://localhost:8080/auth/google/callback'
}
RestClient.post 'https://accounts.google.com/o/oauth2/auth', data
end

end
end
end

context 'GET Index' do
it 'it renders the index template' do
get :index
expect(response).to render_template(:index)
end

let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'should return all the spreadhseets' do
c = SpreadsheetsController.new
r = c.instance_eval{index}
expect(r.count).to eq(Spreadsheet.count)
sheet
get :index
expect(assigns(:spreadsheets)).equal?(Spreadsheet.all.to_a.count)
end
end

context 'GET New' do
it 'opens authentication page on calling auth/google' do
stub_request(:get, 'http://localhost:8080/auth/google/').to_return(google_auth_response)
stub_request(:get, "https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=367225507767-119uvbhdadqbft2kn4759rodoiivksn9.apps.googleusercontent.com&prompt=consent&redirect_uri=http://localhost:8080/auth/google/callback&response_type=code&scope=https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/drive%20https://spreadsheets.google.com/feeds&state=df37c7da59cf8f7a4899cd5a67a612e9d18946664bc98d4f").
with(:headers => {'Accept'=>'*/*; q=0.5, application/xml', 'Accept-Encoding'=>'gzip, deflate', 'Cookie'=>'_lightair_session=Uy9SNDQ1LzZFandLd1g4S2VVTEptR3ZRa0RBcnNFWGtZbG1VZmNKMzc5Z1F6cDFuaHBCa2lScHcxL1FBQ044RTJZMU9iUWF2UitaVjQxcGVzeUZwS0Q3NkdXdzg2SHB6S0IrcU1sR2ExelhRRVZuWFF6MFpraktBMTNCcTM4UVZ5a01ReitYSzNYT2M0dXR1NWViUjhvVGVxUnYwRUtLREtoQUVjMkJPMW1PZG14MUVUQlN0Q2hkRUh5blVLMDZRLS1OZ3JGQXFWQmJKMGNCWGszQWoyMkNRPT0=--8345e9f7215c9ef812febd3588c505cfaef628c1', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
it 'creates new spreadsheet when no access_token given' do
VCR.use_cassette 'controllers/api-new_tokens' do
request.env['omniauth.auth'] = {
'credentials' => {
'token' => 'ya29.QgC-5kYKwAzcdh8AAABnuwXicpaXRvO_YSlv4V9J556542KazsYWEia63TlRyA',
'refresh_token' => '1/DlAqfSUji69F3YuVAHSoWxWE0grR8aYSkb2OocVCNBw',
'expires_at' => Time.now,
'expires' => true
}
}

get :new
expect(response).to render_template(:new)
end
end

let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'does not creates new spreadsheet when access_token is given' do
VCR.use_cassette 'controllers/api-response' do
get(:new, access_token: sheet.access_token)
expect(response).to render_template(:new)
end
end
end

context 'Get Edit' do
let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'renders index page after executing' do
get :edit, title: 'namecollection', id: sheet['spreadsheet_id'], token: sheet['access_token']

expect(response).to render_template(:index)
end

it 'adds spreadsheet\'s credentials' do
get :edit, title: 'namecollection', id: sheet['spreadsheet_id'], token: sheet['access_token']
expect(assigns(:error)).to be(nil)
end
end

context 'Post Update' do
let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'updates the spreadsheet' do
VCR.use_cassette 'controllers/api-update-with-data', record: :new_episodes do
post :update, id: sheet
expect(response).to redirect_to users_path
end
end
end

context 'Post Destroy' do
let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'deletes spreadsheets from database' do
sheet
count1 = Spreadsheet.all.count
post :destroy, id: sheet
count2 = Spreadsheet.all.count

expect(count1).to be(count2 + 1)
end

it 'redirects to spreadsheets index page' do
post :destroy, id: sheet
expect(response).to redirect_to spreadsheets_path
end
end

context 'Get Failure' do
it 'renders index page when user does not accepts permissions' do
get :failure, message: 'access_denied'

expect(response).to render_template(:index)
end

it 'to give a failure message when it fails' do
get :failure, message: 'access_denied'
expect(assigns(:msg)).not_to be nil
end

it 'not to give a failure message when it does not fails' do
get :failure, message: 'access_granted'
expect(assigns(:msg)).to be nil
end

let(:sheet) { FactoryGirl.create(:spreadsheet)}
it 'gets all the spreadsheets' do
sheet
get :failure, message: 'access_denied'

RestClient.get('http://localhost:8080/auth/google/')
expect(assigns(:spreadsheets).count).equal?(Spreadsheet.all.count)
end
end
end
7 changes: 6 additions & 1 deletion spec/factories/spreadsheets.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Read about factories at https://github.com/thoughtbot/factory_girl

FactoryGirl.define do
factory :spreadsheet do
factory :spreadsheet do |s|
s.spreadsheet_id {'1g2JX-w0XtcWD7yZo-K3cSHs7PhycCwhaYYmwajsLIwE'}
s.spreadsheet_title {'namecollection'}
s.access_token {'ya29.QgC-5kYKwAzcdh8AAABnuwXicpaXRvO_YSlv4V9J556542KazsYWEia63TlRyA'}
s.refresh_token {'1/DlAqfSUji69F3YuVAHSoWxWE0grR8aYSkb2OocVCNBw'}
s.expires_at {Time.now - 3600}
end
end
Loading

0 comments on commit c472969

Please sign in to comment.