Test an HTTPS (SSL) request in RSpec Rails

我是研究僧i 提交于 2019-12-17 23:08:20

问题


I'd like to take advantage of the force_ssl feature in rails 3.1rc4.

class ApplicationController < ActionController::Base
  force_ssl
end

Problem is this breaks most/all of my existing RSpec controller specs. For example, this fails:

describe "GET 'index'" do
  it "renders the Start page" do
    get :index
    response.should render_template 'index'
  end
end

Instead of rendering the page the response is a 301 redirect to https://test.host/.

How can I change my specs to simulate an HTTPS GET/POST?

And do I have to change each test manually or is there an easier way? (I realise I could invoke force_ssl only in production, but that's not ideal. Really, I should be testing that force_ssl does indeed redirect to https:// when expected.)


回答1:


To instruct RSpec to make SSL requests in a controller spec use:

request.env['HTTPS'] = 'on'

In your example this looks like:

describe "GET 'index'" do
  it "renders the Start page" do
    request.env['HTTPS'] = 'on'
    get :index
    response.should render_template 'index'
  end
end



回答2:


For rspec 3 syntax, https://stackoverflow.com/a/28361428/1107433

get :index, protocol: 'https://'

There may be a slight different version that above code doesn't work. So use code below:

get :index, protocol: :https




回答3:


If you need SSL at all, anywhere in your application, you should use it everywhere in your application. Then all you need is to use the rack-ssl gem and add the Rack::SSL middleware to your config/environments/production.rb. No additional testing needed; no breakage; problem solved.



来源:https://stackoverflow.com/questions/6785261/test-an-https-ssl-request-in-rspec-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!