Simple way to test an HTTPS (SSL) request with RSp

2019-05-26 08:11发布

问题:

I want Rspec to request the root using https. This is what I currently have:

it "requesting root (/) with HTTPS should return 200" do
  get "https://test.host/"
  last_response.should be_ok
end

Attempting the solution proposed in Test an HTTPS (SSL) request in RSpec Rails returns the following error:

wrong number of arguments (0 for 1)

I would assume I could do something like:

get "/", :https => "on"

Is there a way to request the root without specifying the host?

回答1:

When using Sinatra and RSpec, you are using the #get/#post methods provided by Rack::Test, so I suggest you look there to see how they work: https://github.com/brynary/rack-test/blob/master/lib/rack/test.rb

As you can see, they take an optional env Hash, where you can set "HTTPS" to "on", like this:

get '/', {}, {'HTTPS' => 'on'}

If you want to set it by default for all your requests, you need to override the Rack::Test::Session#default_env method, and had 'HTTPS' => 'on' to it (I suggest doing it in your spec_helper.rb), like this:

class Rack::Test::Session
  def default_env
    { "rack.test" => true, "REMOTE_ADDR" => "127.0.0.1", "HTTPS" => 'on' }.merge(headers_for_env)
  end
end


回答2:

The previous answer with the Rack::Test:Session change did not work for me in rails 4.1.1. Instead I am now using the Rails RSpec bindings to force force all integration tests into https. To do this add the following code to spec_helper.rb:

class ActionDispatch::Integration::Session
  def https?
    true
  end
end