I come into the task for implementing https redirect for my app. After discuss with team, we should to go with simple redirect way.
And this is the the code in controller:
application_controller.rb (version 1)
class ApplicationController < ActionController::Base
...
def self.force_ssl(options = {})
return unless ENV["FORCE_SSL"].present?
host = options.delete(:host)
before_filter(options) do
if !request.ssl? && params[:controller] != "health_check"
redirect_to request.url.gsub("http://", "https://")
end
end
end
force_ssl
...
end
The problem is when I stub the ENV['FORCE_SSL'] in controller test. It not work. ENV is correctly stub when run pry.binding in test suite but when I run pry.binding in force_ssl method when test is running, ENV['FORCE_SSL'] is nil.
Code in spec file:
require 'rails_helper'
RSpec.describe ApplicationController, type: :controller do
controller do
def index
redirect_to root_path
end
end
it "redirect to https when request in http" do
allow(ENV).to receive(:[]).with('FORCE_SSL').and_return('true')
get 'index', protocal: :http
expect(response).to redirect_to %r(\Ahttps://)
end
end
After that, when I change force_ssl to instance method gracefully.
application_controller.rb (version 2)
class ApplicationController < ActionController::Base
...
before_action :force_ssl
private
def force_ssl
return unless ENV["FORCE_SSL"].present?
if !request.ssl? && params[:controller] != "health_check"
redirect_to request.url.gsub("http://", "https://")
end
end
...
end
Just want to know the reason why this happen and are there any way to stub the ENV for test with version 1 controller code ?
Aucun commentaire:
Enregistrer un commentaire