[RUBY] How to write test code with Basic authentication

【Overview】

1. Conclusion </ b>

2. When is it going to be ○○ </ b>

Supplement: Development environment </ b>

  1. Conclusion

Embed an environment variable in a variable and use visit to jump to the URL where the environment variable is embedded </ b>!

  1. How to describe

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 'Post a comment', type: :system do
  before do
    @time = FactoryBot.create(:time)
    @comment = Faker::Lorem.sentence
  end

  it 'Logged-in users can comment on the self-learning post details page' do
    #log in
    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

I wrote it as above!

❶ Since the specific example of the URL below is not an environment variable, I assigned the environment variable to the variable. After that, I imitated the following URL. ❷ If you do not write the basic_pass method before the integration test code is loaded, you will not be able to pass the basic authentication test ID and password. Therefore, I code it at the very beginning of the integration test code and move to the new registration screen (using devise gem).

URL that was quite helpful: How to pass Basic authentication with Capybara + Headless Chrome (System Spec)

Supplement: Development environment

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

Recommended Posts