我设置了一个处理omniauth身份验证的控制器,这些身份验证可以在自定义构建的身份验证系统中使用。我正在尝试测试如何处理身份验证的逻辑(例如:如果用户已经/没有帐户,如果用户当前没有登录,等等)。因此我有一个授权模型和一个授权控制器。创建授权的操作有以下概要:
class AuthorizationsController < ApplicationController
def create
omniauth = request.env['omniauth.auth']
authorization = Authorization.find_by_provider_and_uid(omniauth['provider'], omniauth['uid'])
if authorization
# Authorization already established, log in user
elsif current_user
# User is logged in but wants to add another omniauth authentication
else
# Create user and associate them with omniauth authentication
end
end
end
我试图在Rspec中测试这个逻辑,但一直有问题。 Heres是我在我的规范中使用的:
describe AuthorizationsController do
render_views
describe "POST 'create'" do
describe "with an already existing authorization" do
it "should log the user in" do
@authmock = mock_model(Authorization)
Authorization.should_receive(:find_by_provider_and_uid).and_return(@authmock)
post :create, :provider => 'twitter'
current_user?(@authmock.user).should == true
response.should redirect_to(root_path)
end
end
end
end
我的印象是,在进行赋值调用时,这应该将我的模拟授权模型(@authmock)分配给控制器中的局部变量授权,从而使'if authorization'返回true。但是每当我真的运行此规范时,我都会收到此错误:
Failures:
1) AuthorizationsController POST 'create' with an already existing authorization should log the user in
Failure/Error: post :create, :provider => 'twitter'
NoMethodError:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
# ./app/controllers/authorizations_controller.rb:5:in `create'
# ./spec/controllers/authorizations_controller_spec.rb:16:in `block (4 levels) in <top (required)>'
任何人都可以告诉我这里我做错了什么吗?
修改
因为提出了关于omniauth的分配是否导致问题的问题,我评论了该行以查看会发生什么并得到以下错误:
1) AuthorizationsController POST 'create' with an already existing authorization should log the user in
Failure/Error: post :create, :provider => 'twitter'
NameError:
undefined local variable or method `omniauth' for #<AuthorizationsController:0xb41809c>
# ./app/controllers/authorizations_controller.rb:5:in `create'
# ./spec/controllers/authorizations_controller_spec.rb:16:in `block (4 levels) in <top (required)>'
告诉我问题出在mock或stub上,因为find_by_provider_and_uid函数仍在评估中,并且在测试运行时没有存根
答案 0 :(得分:0)
你在猜测吗
current_user?(@authmock.user).should == true
或
response.should redirect_to(root_path)
我认为不应该在这里测试第一个期望,因为你已经嘲笑'如果授权'阻止,那么你应该说明当时会发生什么!