在RSpec Rails中测试HTTPS(SSL)请求
我想利用rails 3.1rc4中的force_ssl
function 。
class ApplicationController < ActionController::Base force_ssl end
问题是这打破了我现有的RSpec控制器规格的大部分/全部。 例如,这失败了:
describe "GET 'index'" do it "renders the Start page" do get :index response.should render_template 'index' end end
而不是呈现页面响应是301重定向到https://test.host/
。
如何更改我的规范以模拟HTTPS GET / POST?
我是否必须手动更改每个测试或是否有更简单的方法? (我意识到我只能在生产中调用force_ssl
,但这并不理想。实际上,我应该测试force_ssl
确实会在预期时重定向到https://。)
要指示RSpec在控制器规范中发出SSL请求,请使用:
request.env['HTTPS'] = 'on'
在您的示例中,这看起来像:
describe "GET 'index'" do it "renders the Start page" do request.env['HTTPS'] = 'on' get :index response.should render_template 'index' end end
对于rspec 3语法, 请访问https://stackoverflow.com/a/28361428/1107433
get :index, protocol: 'https://'
可能存在略微不同的版本,上面的代码不起作用。 所以使用下面的代码:
get :index, protocol: :https
如果您在应用程序的任何位置都需要SSL,则应在应用程序的任何位置使用它。 然后,您只需使用rack-ssl
gem并将Rack::SSL
中间件添加到config/environments/production.rb
。 无需额外测试; 没有破损; 问题解决了。