为什么这个简单的迷你测试失败了?

Why is this simple minitest failing?

我是测试 rails 应用程序的新手,因为我通常只是进行手动测试...但这次我正在尝试以正确的方式进行测试。

为什么这个基本测试失败了?

test "once you go to to app you are asked to sign in" do
  get "/"
  assert_redirected_to "/users/sign_in"
  assert_select "title", "Home Sign-In"
end

第一个断言成功但第二个断言不成功。当我查看源代码时,标题似乎是正确的。

<title>Home Sign-In</title>

如果您的控制器方法中有重定向调用,它实际上并没有呈现。这就是为什么你不能使用 assert_select.

您可以尝试将您的测试用例分成两部分:

test "once you go to to app you are asked to sign in" do
  get "/"
  assert_redirected_to "/users/sign_in"
end

test "sign in page title is correct" do
  get "/users/sign_in"
  assert_select "title", "Home Sign-In"
end

@Pavel 是对的。 获取请求后检查响应的一种简单方法是 @response.body。 所以在你的情况下

test "once you go to to app you are asked to sign in" do
  get "/"
  assert_redirected_to "/users/sign_in"
  byebug #print @response.body here. At this point @response.body will
  # be "You are being redirected to /users/sign_in".
  assert_select "title", "Home Sign-In"
 end

因此您可以按照 Pavel 的建议

进行修改
test "sign in page title is correct" do
  get "/users/sign_in"
  assert_select "title", "Home Sign-In"
end