gpt4 book ai didi

ruby-on-rails - rspec 简单示例在集成测试中请求变量出错

转载 作者:行者123 更新时间:2023-12-04 06:08:57 28 4
gpt4 key购买 nike

这是一个未经测试的采用的 Rails 应用程序。我正在尝试在集成测试中测试 omniauth 但出现错误(编辑 我基于此:https://github.com/intridea/omniauth/wiki/Integration-Testing)。这反射(reflect)了我对 Rspec 的理解不足。看起来请求对象默认可用。

我的 spec/spec_helper.rb 中有:

config.include IntegrationSpecHelper, :type => :request
Capybara.default_host = 'http://localhost:3000'

OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:facebook, {
:uid => '12345'
})

在我的 spec/integration/login_spec 中:

require 'spec_helper'

describe ServicesController, "OmniAuth" do
before do
puts OmniAuth.config.mock_auth[:facebook]
puts request # comes back blank
request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
end

it "sets a session variable to the OmniAuth auth hash" do
request.env["omniauth.auth"][:uid].should == '12345'
end
end

我收到以下错误:

{"provider"=>"facebook", "uid"=>"12345", "user_info"=>{"name"=>"Bob Example"}}

F

Failures:

1) ServicesController OmniAuth sets a session variable to the OmniAuth auth hash Failure/Error: request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook] NoMethodError: undefined method env' for nil:NilClass
# ./login_spec.rb:8:in
block (2 levels) in '

Finished in 22.06 seconds 1 example, 1 failure

Failed examples:

rspec ./login_spec.rb:11 # ServicesController OmniAuth sets a session variable to the OmniAuth auth hash

默认情况下,请求对象应该在这里可用吗?此错误是否可能意味着其他原因?

谢谢

最佳答案

你得到 nil 因为你还没有提出任何请求。

要使测试正常进行,您必须做三件事:

  1. 设置模拟
  2. 提出要求
  3. 测试附加到回调的任何代码

这是我的做法。首先在before block 中设置mock,然后访问provider对应的URL(本例为facebook):

before do
OmniAuth.config.add_mock(:facebook, {:uid => '12345'})
visit '/auth/facebook'
end

来自wiki :

A request to /auth/provider will redirect immediately to /auth/provider/callback.

所以你必须有一个匹配 '/auth/:provider/callback' 的路由。您映射的任何操作都必须执行上面第 3 步中的内容。

如果您想测试 session 变量是否设置为 uid,您可以这样做(之所以有效,是因为您在上面的模拟中将 uid 设置为“12345”):

it "sets a session variable to the OmniAuth auth hash" do
session['uid'].should == '12345'
end

下面是应该通过的路线和 Action :

路线.rb

match '/auth/:provider/callback' => 'sessions#callback'

controllers/sessions_controller.rb

def callback
session['uid'] = request.env["omniauth.auth"][:uid]
end

这就是它的要点。希望对您有所帮助。

关于ruby-on-rails - rspec 简单示例在集成测试中请求变量出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11710660/

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