LoginSignup
6
4

More than 3 years have passed since last update.

Basic認証を交えたテストコードの書き方

Last updated at Posted at 2020-09-27

【概要】

1.結論

2.どのように記載するのか

補足:開発環境

1.結論

環境変数を変数に埋め込み、visitでその環境変数を埋め込んだURLに飛ぶようにする!

2.どのように記載するのか

def basic_pass(path) #---❶
  username = ENV["STUDY"] 
  password = ENV["STUDY_password"]
  visit "http://#{username}:#{password}@#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}#{path}"
end

RSpec.describe 'コメント投稿', type: :system do
  before do
    @time = FactoryBot.create(:time)
    @comment = Faker::Lorem.sentence
  end

  it 'ログインしたユーザーは自己学習投稿の詳細ページでコメントできる' do
    # ログインする
    basic_pass new_user_session_path #---❷
    fill_in 'Email', with: @time_report.user.email
    fill_in 'Password', with: @time_report.user.password
    find('input[name="commit"]').click
    expect(current_path).to eq root_path
  end
end

上記のように記載しました!

❶下記のURLの具体例は環境変数になっていないので、変数に環境変数を代入する形にしました。あとは下記のURLを真似させていただきました。
❷basic_passメソッドを結合テストコードが読み込まれる前に記載しないとBasic認証テストのID,パスワードを通過できません。なので、結合テストコードの内容の一番最初にコーディングし、新規登録画面(devise gem使用)に遷移するようにしています。

かなり参考にしたURL:
Capybara + Headless Chrome (System Spec) で Basic認証 を通過する方法

補足:開発環境

Ruby 2.6.5
Rails 6.0.3.3
MySQL
Visual Studio Code
(Caprybara,Rspec,GoogleChrome)

6
4
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
6
4