HTTPS 通信のテスト ; Rspec

HTTPS 通信の Unit Test を Rspec で実現するには

request.env['HTTPS'] を 'on' か 'off' にするだけ

テストケースは漏れ漏れだが、簡単に


準備

モデル設計に意味は無し

$ rails g controller top index
$ rails g scaffold Book title:string
$ rake db:migrate RAILS_ENV=test
$ rails g rspec:install

app/controllers/book_controller.rb

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]
  force_ssl if: :ssl_configured?

  def index
  end
  ...

  private

  def ssl_configured?
    Rails.env.test? or Rails.env.development?
  end
end

spec/controllers/books_controller.rb

require 'spec_helper'

describe BooksController do

  describe "GET index" do
    context 'access using SSL' do
      before do
        request.env['HTTPS'] = 'on'
        get :index
      end 
      it { response.should be_success }
    end 

    context 'access not using SSL' do
      before do
        request.env['HTTPS'] = 'off'
        get :index
      end 
      it { response.should_not be_success }
    end 
  end 

end

引用元 # 勉強になります

Rails+RspecでSSL・非SSLのテストするときはshared_context使うと捗る - Qiita

Test an HTTPS (SSL) request in RSpec Rails - Stack Overflow