概要
- 表題通り
- rspec —profile で計測した
方法
- パラメータが間違っている時root_pathへリダイレクトするアクションを実装し、リダイレクトの可否を検証するテストコードをrequestとcontrollerにそれぞれ書いた。
- テストコードの動作速度を
rspec —profile
コマンドの出力で計測した。
結果
- 3回計測し平均値を算出しrequestとcontrollerのrspecの動作速度を比較したところ、controlerのテストコードの方が動作速度が短かった。
- リダイレクトと描画テスト間の動作速度を比較したところ、ページを描画するテストコードの方が速く実行されていた。
- entryページの描画についてはrequestとcontroller間で差異は認められなかった。
考察
- capybaraが遅いのかもしれない
コード
app側
-
/users/entry/:token
にアクセスしtokenが正しい時はそのまま描画し、間違っている時はroot_pathへリダイレクトするアクション
app/controllers/users_controller.rb
class UsersController < ApplicationController
def entry
if token_valid?(params[:token])
render :entry
else
redirect_to root_path
end
end
private
def token_valid?(token)
if User.find_by(token: token).present?
true
else
false
end
end
end
rspec側
factory
- tokenを持つuserのfactorygirlデータ
spec/factories/user.rb
FactoryGirl.define do
factory :user do
token: 'oooooooooo'
end
end
テストコード
- requestのrspec
spec/requests/users_pages_spec.rb
require 'spec_helper'
describe 'entry page' do
let(:user) { FactoryGirl.create(:user) }
let(:valid_token) { user.token }
let(:invalid_token) { 'xxxxxxxxxxxxx' }
context '存在しないtokenでentryページにアクセスした場合' do
it 'root_pathへリダイレクト' do
visit users_entry_path(token: invalid_token)
expect(current_path).to eq(root_path)
end
end
context 'userに存在するtokenでentryページにアクセスした場合' do
it 'entryページを描画' do
visit users_entry_path(token: valid_token)
expect(current_path).to eq(users_entry_path(token: valid_token))
end
end
end
controllerのrspec
spec/controllers/users_controller_spec.rb
require 'spec_helper'
describe UsersController do
let(:user) { FactoryGirl.create(:user) }
let(:valid_token) { user.token }
let(:invalid_token) { 'xxxxxxxxxxxxx' }
context '存在しないtokenでentryページにアクセスした場合' do
it 'root_pathへリダイレクト' do
get :entry, token: invalid_token
expect(response).to redirect_to root_path
end
end
context 'userに存在するtokenでentryページにアクセスした場合' do
it 'entryページを描画' do
get :entry, token: valid_token
expect(response).to render_template :entry
end
end
end