LoginSignup
30
31

More than 5 years have passed since last update.

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

Posted at

RailsのコントローラのSSL・非SSLのときの振る舞いをテストするには request.env['HTTPS']'on''off' を代入すればいい。

describe SomeController do
  describe 'GET new' do
    context 'access using SSL' do
      before { request.env['HTTPS'] = 'on' }
      it do
        get :new # SSLでアクセスする
      end
    end

    context 'access not using SSL' do
      before { request.env['HTTPS'] = 'off' }
      # この中は非SSL
    end
  end
end

毎回 before ブロックを書くのは面倒くさいので shared_context を使うと捗る。以下の様なコードを用意する。

shared_context 'SSL', ssl: true do
  before { request.env['HTTPS'] = 'on' }
end

shared_context 'not SSL', ssl: false do
  before { request.env['HTTPS'] = 'off' }
end

すると以下のように書ける。

describe SomeController do
  describe 'GET new' do
    context 'access using SSL', ssl: true do
      it do
        get :new # SSLでアクセスする
      end
    end

    context 'access not using SSL', ssl: false do
      # この中は非SSL
    end
  end
end
30
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
31