При написании интеграционных тестов для приложения Rails 5 я столкнулся с печально известной страницей «Вы перенаправляетесь», без каких-либо очевидных причин. Есть два весьма похожих тестов:Rails - Почему я получаю «Вы перенаправлены» в тесте интеграции?
test "GETtting correct activation link on an already activated user gives error message and redirects to root url" do
# GIVEN a non-yet-registered email address
email_address = "[email protected]"
# GIVEN the sign-up page has been displayd
get signup_path
# GIVEN new user is created
post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
# GIVEN the URI from activation email
activation_uri = URI.extract(ActionMailer::Base.deliveries.last.text_part.body.encoded)[0]
# GIVEN the URI's been used and the user is already activated
get activation_uri
# WHEN reading back the newly activated user
activated_user = User.find_by_email(email_address)
# EXPECT the user to be activated
assert activated_user.activated?
# WHEN using the activation link on an already activated user
get activation_uri
# EXPECT redirection to root path
assert_redirected_to root_url
follow_redirect!
# EXPECT flash message
assert_not flash.empty?
# EXPECT rendered page to contain activation error information
assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end
который заканчивает правильно, и следующий:
test "GETtting incorrect activation hash on a non-activated user gives error message and redirects to root url" do
# GIVEN a non-yet-registered email address
email_address = "[email protected]"
# GIVEN the sign-up page has been displayd
get signup_path
# GIVEN new user is created
post signup_path, params: { user: { email: email_address, email_confirmation: email_address, password: "testpassword", password_confirmation: "testpassword" } }
# WEHN GETting the activation URI with invalid activation hash
activation_uri = "http://localhost:3000/account_activations/waTbfcCoZoPTBEIcewsl8Q/edit?email=#{ERB::Util.url_encode(email_address)}"
get activation_uri
# EXPECT redirection to root path
assert_redirected_to root_url
follow_redirect!
# EXPECT flash message
assert_not flash.empty?
# EXPECT rendered page to contain activation error information ('You are being redirected' rendered here)
assert_select 'div#flash div h5', text: I18n.translate('users.activate.error')
end
, который с треском проваливается на последнем утверждают, потому что «вы будете перенаправлены» визуализируется вместо page Я ожидаю, что будет оказана. В обоих случаях я использую follow_redirect!
, а первый работает, а второй - нет. Статический URL-адрес во втором тесте правильный. Он использует только действительный, но не связанный хэш вместо ожидаемого. В контроллере есть простой
flash[:error] = "#{t'users.activate.error'}"
redirect_to root_url
в обоих случаях (такой же способ). Я получаю правильный код ответа 302
и правильный URL-адрес перенаправления. При выполнении одних и тех же тестов вручную в браузере исправляется страница. При выполнении тестов я получаю «Вы находитесь ...» во втором тесте.
Любые подсказки?
Хм - ну, я не меняю код. Я получаю правильный 302. Я также получаю правильный URL перенаправления. Тем не менее страница «вы находитесь» отображается, а не переадресация. Когда я использую те же URL-адреса GET в браузере, все работает так, как ожидалось. Единственное различие между двумя вызовами - хеш активации. Я постараюсь поближе рассмотреть поток с неправильным хешем и посмотреть, не отвлекается ли он где-нибудь. – silverdr