LoginSignup
2
1

More than 1 year has passed since last update.

【RSpec】重複するテストコードを共通化しよう

Last updated at Posted at 2021-10-14

重複するテストコードはshared_contextやshared_examplesで共通化できる

rails_helperの設定

下記の記述のコメントアウトを外す

spec/rails_helper.rb
...
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f }
...

↑を忘れると下記のエラーで怒られる

ArgumentError:
  Could not find shared context "hogehoge"

shared_contextで重複するコードをまとめる

spec下にディレクトリを作成して共通化したい処理を記述

spec/support/contexts/login_setup.rb
RSpec.shared_context 'login setup' do
  before do
    Rails.application.env_config["devise.mapping"] = Devise.mappings[:user]
    Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2]
    sign_in user
  end
end

include_context 'login setup'に置き換えるだけ

spec/requests/XXXXX_spec.rb
RSpec.describe "/XXXXX", type: :request do
  describe 'GET /XXXXX' do
    ...
    include_context 'login setup'
    ...
  end
end

shared_examplesで重複するコードをまとめる

shared_contextのときと同じようにファイルを作成する

spec/support/contexts/login_user.rb
RSpec.shared_examples 'login user' do  
  it 'ログインしているユーザーを取得すること' do
    expect(response).to have_http_status(200)
    ...
  end
end
spec/requests/XXXXX_spec.rb
RSpec.describe "/XXXXX", type: :request do
  describe 'GET /XXXXX' do
    context '@user' do
      it_behaves_like 'login user'
    end
  end
end

include_examplesとit_behaves_likeの違い

shared_examplesを使うときはinclude_examplesよりit_behaves_likeを使うほうがよい

include_examplesは定義の上書きが起きてしまうらしい
詳しくは↓

参考

2
1
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
2
1