Hej dodalem proste logowanie za pomoca Gmail do mojej aplikacji:
Tutaj opisze konfiguracje:
routes.rb
match '/auth/gapps/callback', :to => 'sessions#authenticate_gapps'
match '/auth/failure', :to => 'sessions#failure'
match '/logout', :to => 'sessions#logout'
controller application_controller.rb
[code]class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :admin_required
def admin_required
redirect_to ‘/auth/gapps’ unless current_admin
end
def current_admin
@current_admin ||= Admin.find(session[:admin_id]) if session[:admin_id]
end
helper_method :current_admin
end[/code]
controller sessions
[code]skip_before_filter :admin_required
def authenticate_gapps
auth = request.env[“omniauth.auth”]
admin = Admin.find_by_provider_and_uid(auth[“provider”], auth[“uid”]) || Admin.create_with_omniauth(auth)
session[:admin_id] = admin.id
redirect_to ‘/’
end
def failure
render :text => ‘401 Unauthorized’, :status => 401
end
def logout
session[:admin_id] = nil
redirect_to ‘/’
end[/code]
Dane sa przetrzymywane w tabeli Admins:
t.string :provider
t.string :uid
t.string :name
t.timestamps
Uzywam Gema:
gem 'omniauth-google-apps'
initlializer omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_apps, :domain => 'gmail.com', :name => 'gapps'
end
Chcialbym napisac testy. W test_helper zdefiniowalem metode:
def login_with_oauth(service = :gapps)
visit "/auth/#{service}"
end
Dla kontrolera np categories chcialbym napisac testy funkcjonalne:
[code]require ‘test_helper’
class CategoriesControllerTest < ActionController::TestCase
setup do
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:gapps, {
:uid => ‘12345’,
:name => ‘lukasz’
})
@category = categories(:affiliate)
login_with_oauth
end
test “should get index” do
get :index
assert_response :success
assert_not_nil assigns(:categories)
end
end[/code]
Niestety rake test zwraca mi blad:
[code]Error: test_should_get_index(CategoriesControllerTest)
NoMethodError: undefined method visit' for test_should_get_index(CategoriesControllerTest):CategoriesControllerTest test/test_helper.rb:14:in
login_with_oauth’
11:
12: # Add more helper methods to be used by all tests here…
13: def login_with_oauth(service = :gapps)
=> 14: visit “/auth/#{service}”
15: end
16: end
test/functional/categories_controller_test.rb:11:in `block in class:CategoriesControllerTest’
Finished in 0.256582824 seconds.
1 tests, 0 assertions, 0 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications
0% passed[/code]