Ruby on rails rspec在集成测试中获取请求变量错误的简单示例

Ruby on rails rspec在集成测试中获取请求变量错误的简单示例,ruby-on-rails,rspec,Ruby On Rails,Rspec,这是一个采用的rails应用程序,没有测试。我试图在集成测试中测试omniauth,但得到一个错误(edit我基于此:)。这反映了我对Rspec缺乏了解。看起来请求对象在默认情况下是可用的 我的spec/spec_helper.rb中有: config.include IntegrationSpecHelper, :type => :request Capybara.default_host = 'http://localhost:3000' OmniAuth.config.test_m

这是一个采用的rails应用程序,没有测试。我试图在集成测试中测试omniauth,但得到一个错误(edit我基于此:)。这反映了我对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'
})
在我的规范/集成/登录规范中:

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 
我得到以下错误:

{“提供者”=>“facebook”、“uid”=>“12345”、“用户信息”=>{“姓名”=>“Bob” 示例“}}

F

失败:

1) ServicesController OmniAuth将会话变量设置为 OmniAuth验证哈希 失败/错误:request.env[“omniauth.auth”]=omniauth.config.mock_auth[:facebook] 命名错误: nil:NilClass的未定义方法
env'
#./login_spec.rb:8:in
block(2级)in'

在22.06秒内完成1例,1次失败

失败的示例:

rspec./login_spec.rb:11#ServicesController OmniAuth设置会话 OmniAuth身份验证哈希的变量

默认情况下,请求对象是否应该在此处可用?这个错误可能意味着什么吗


thx

您得到的是
nil
,因为您还没有提出任何请求

要使测试正常工作,您必须做三件事:

  • 设置模拟
  • 提出请求
  • 测试任何附加到回调的代码
  • 我是这样做的。首先在之前的
    块中设置模拟,然后访问对应于提供商的URL(在本例中为facebook):

    从:

    对/auth/provider的请求将立即重定向到/auth/provider/callback

    因此,您必须有一个与“/auth/:provider/callback”匹配的路由。您映射的任何操作都必须执行上面步骤3中的内容

    如果要测试会话变量是否设置为uid,可以执行以下操作(这是因为在上面的模拟中将uid设置为“12345”):

    这里有一条路线和行动应该让这一切顺利:

    routes.rb

    match '/auth/:provider/callback' => 'sessions#callback'
    
    控制器/会话\u controller.rb

    def callback
      session['uid'] = request.env["omniauth.auth"][:uid]
    end
    
    这就是要点。希望有帮助

    match '/auth/:provider/callback' => 'sessions#callback'
    
    def callback
      session['uid'] = request.env["omniauth.auth"][:uid]
    end