gpt4 book ai didi

ruby-on-rails - 设计 Controller 测试 - ActionController::UrlGenerationError

转载 作者:行者123 更新时间:2023-12-04 06:25:18 27 4
gpt4 key购买 nike

我在我的 Rails 应用程序中通过设计使用 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'
})

Controller :
#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',但我不知道解决这个问题的正确方法。

最佳答案

万一有人像我一样偶然发现这个寻找答案。
我在添加第二个 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]

关于ruby-on-rails - 设计 Controller 测试 - ActionController::UrlGenerationError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803483/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com