【发布时间】:2017-04-01 05:25:17
【问题描述】:
在为 Rails 5 应用程序编写集成测试时,我遇到了臭名昭著的“您正在被重定向”页面,对我来说没有明显的原因。有两个高度相似的测试:
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 = "tester@testing.net"
# 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 = "tester@testing.net"
# 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
在最后一个断言中惨遭失败,因为正在呈现“您正在被重定向”而不是我期望呈现的页面。在这两种情况下,我都使用follow_redirect!,第一个有效,而第二个无效。第二个测试中的静态 URL 是正确的。它只使用一个有效但不相关的散列而不是预期的散列。在控制器中有简单的
flash[:error] = "#{t'users.activate.error'}"
redirect_to root_url
在这两种情况下(相同的方法)。我收到正确的302 响应代码和正确的重定向 URL。在浏览器中手动执行相同的测试时,会呈现正确的页面。在运行测试时,我在第二个测试中得到“你正在……”。
有什么线索吗?
【问题讨论】:
标签: ruby-on-rails redirect integration-testing