概要
あまりユースケースはないと思いますが、
Capybara使ったfeature(system) specで、Basic認証を突破したい時。
基本的にspecは本番環境のテストなので、Basic認証は使わないという本質的なことは置いておいてとりあえずテストしたいんだってときの雑実装です。
コード
Feature spec
RSpec.feature 'hoge' do
describe 'GET /hoge' do
let(:url) { '/hoge'}
background do
name='name'
password='password'
Capybara.app_host = "http://#{name}:#{password}@#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}"
end
it 'success' do
visit(url)
expect(page).to have_content('fuga')
end
end
end
shared_contextにする場合はこんな感じ
shared_context 'basic_authentication' do
background do
name='name'
password='password'
Capybara.app_host = "http://#{name}:#{password}@#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}"
end
end
RSpec.feature 'hoge' do
describe 'GET /hoge' do
let(:url) { '/hoge'}
include_context 'basic_authentication'
it 'success' do
visit(url)
expect(page).to have_content('fuga')
end
end
end