问题描述
我得到 URI::InvalidURIError
测试 Rails Home 控制器:
I get URI::InvalidURIError
testing Rails Home controller:
require 'test_helper'
class HomeControllerTest < ActionDispatch::IntegrationTest
test "should get index" do
get :index
assert_response :success
end
end
出现以下错误:
E
Error:
HomeControllerTest#test_should_get_index:
URI::InvalidURIError: bad URI(is not URI?): http://www.example.com:80index
test/controllers/home_controller_test.rb:7:in `block in <class:HomeControllerTest>'
堆栈如下:
Rails 5.0.0.beta3
minitest (5.8.4)
推荐答案
Controller 测试继承自 ActionController::TestCase
,而你的测试继承自 ActionDispatch::IntegrationTest
.所以您使用的是集成测试而不是控制器测试.
Controller tests inherit from ActionController::TestCase
, while your testinherits from ActionDispatch::IntegrationTest
. So you're using an integration test and not a controller test.
错误是:
http://www.example.com:80index
这看起来不对,是吗?;-)
That doesn't look right, does it? ;-)
解决方案是使用完整路径:
get '/index'
请记住,集成测试并没有真正绑定到任何特定的控制器(或其他任何东西,就此而言).他们测试应用程序中多个组件的集成.因此,如果您正在测试 UserController
的 index
操作,您可能需要使用 /users/index
.
Remember, integration tests aren't really tied to any specific controller (or anything else, for that matter). They test the integration of several components in your application. So if you're testing the index
action of a UserController
you'd probably need to use /users/index
.
如果您打算进行控制器测试而不是集成测试,您需要设置正确的超类.使用 get :index
(对于 index 方法)应该可以正常工作.
If you intended to make a controller test and not an integration test, you want to set the correct superclass. Using get :index
(for the index method) should work fine then.
这篇关于URI::InvalidURIError: 错误的 URI(不是 URI?)测试 Rails 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!