在RSpec Rails中测试HTTPS(SSL)请求

nau*_*ter 18 ssl https rspec ruby-on-rails ruby-on-rails-3.1

我想利用rails 3.1rc4 中的force_ssl功能.

class ApplicationController < ActionController::Base
  force_ssl
end
Run Code Online (Sandbox Code Playgroud)

问题是这打破了我现有的RSpec控制器规格的大部分/全部.例如,这失败了:

describe "GET 'index'" do
  it "renders the Start page" do
    get :index
    response.should render_template 'index'
  end
end
Run Code Online (Sandbox Code Playgroud)

而不是呈现页面的响应是301重定向到https://test.host/.

如何更改我的规范以模拟HTTPS GET/POST?

我是否必须手动更改每个测试或是否有更简单的方法?(我意识到我force_ssl只能在生产中调用,但这并不理想.真的,我应该测试force_ssl确实会在预期时重定向到https://.)

Wil*_*ler 42

要指示RSpec在控制器规范中发出SSL请求,请使用:

request.env['HTTPS'] = 'on'
Run Code Online (Sandbox Code Playgroud)

在您的示例中,这看起来像:

describe "GET 'index'" do
  it "renders the Start page" do
    request.env['HTTPS'] = 'on'
    get :index
    response.should render_template 'index'
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 对于实际的_request_规范(与现在已弃用的控制器规范相反),它的工作方式如下:`get"/ path",headers:{"HTTPS"=>"on"}`.Rack :: Request将接收HTTPS标头,告知线路上的所有内容,将请求视为SSL/TLS请求. (5认同)
  • 我正在使用rspe 2.11.0,我总是得到这个错误消息:"未定义的方法`env'为nil:NilClass". (3认同)