我在我的Rails应用程序中通过Devise使用OmniAuth。我正在尝试测试我的回调方法是否正确调用并正常运行。我目前在运行规范时收到错误。
错误:
Failure/Error: get user_omniauth_authorize_path(:facebook)
ActionController::UrlGenerationError:
No route matches {:action=>"/users/auth/facebook", :controller=>"users/omniauth_callbacks"} missing required keys: [:action]
我的规格:
#spec/controllers/users/omniauth_callbacks_controller_spec.rb
require 'rails_helper'
RSpec.describe Users::OmniauthCallbacksController, :type => :controller do
context 'get facebook' do
before do
request.env["devise.mapping"] = Devise.mappings[:user] # If using Devise
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end
it 'should create user, redirect to homepage, and create session' do
get user_omniauth_authorize_path(:facebook)
expect(response).to redirect_to(user_omniauth_callback_path)
end
end
end
支持文件:
#spec/support/omniauth.rb
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
:provider => 'facebook',
:uid => '123545',
:email => 'fake@fake.com'
})
控制器:
#app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
@user = User.from_omniauth(request.env['omniauth.auth'])
if @user.persisted?
sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
set_flash_message(:notice, :success, :kind => 'Facebook') if is_navigational_format? #todo what is this doing
else
session['devise.facebook_data'] = request.env['omniauth.auth']
redirect_to new_user_registration_url
end
end
end
路线:
devise_for :users, :controllers => { :omniauth_callbacks => 'users/omniauth_callbacks' }
我认为问题在于如何进行路由。我认为行动应该只是'facebook'而不是'/ users / auth / facebook',但我不知道解决这个问题的正确方法。
答案 0 :(得分:1)
如果有人偶然发现这个问题,就像我一样寻找答案。 添加第二个Omniauth策略时遇到了这个问题。事实证明,问题是我要在我的模型声明中包含策略
例如,我已经使用谷歌授权了
# app/models/user.rb
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:google]
但后来想添加第二个提供商(例如facebook)。我忘了将facebook添加到omniauth提供程序列表中,因此在我的规范运行时出现了错误。我通过改为
来修复它# app/models/user.rb
devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:google,:facebook]
答案 1 :(得分:0)
我收到与您相同的错误missing required keys: [:action]
。在我阅读RSpec文档后,我发现get
的参数应该类似:index
(动作名称)。因为我定义了:
# app/controllers/users/omniauth_callbacks_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
# ...
end
end
所以我将get user_omniauth_authorize_path(:facebook)
更改为get :facebook
并添加了一些omniauth模拟。现在它过去了!