在 Rails 3 中,当在 MiniTest 中编写功能测试时,我养成了将路由测试与 Controller 操作分开测试的习惯。我从 Rails Guide on Testing - Section 9: Testing Routes 得到了这个想法.然而,在将我的应用程序升级到 Rails 4 之后,我注意到如果我不为 get|patch|post|delete
方法提供一组适当的参数。
例如,给定路线:
# config/routes.rb
namespace "api" do
namespace "v2", defaults: { format: :json } do
resources :users do
resources :posts do
resources :comments
end
end
end
end
和功能测试:
# test/controllers/api/v2/comments_controller_test.rb
describe Api::V2::CommentsController
it "does something" do
get :index
end
end
在 Rails 3 中,上面的代码可以工作。但是在 Rails 4 中我得到一个 URL 生成错误:
ActionController::UrlGenerationError: No route matches {:action=>"index", :controller=>"api/v2/comments"}
据此我可以推断,get
助手在尝试定位 Controller 和操作时根本无法匹配路由文件中的路由。很公平。我可以通过更改 get
调用以包含满足嵌套路由所需的参数来解决此问题,如下所示:
# test/controllers/api/v2/comments_controller_test.rb
describe Api::V2::CommentsController
it "does something" do
get :index, { user_id: "1", post_id: "1" }
end
end
...然后一切又好了。
所以我的问题是,由于在 Rails 3 中不是这种情况,现在是否可以信任 Controller Action 测试来完全测试/验证我在 Rails 4+ 中的路由?或者在测试路线方面还有其他优势吗?是否存在路由测试涵盖而 Controller Action 测试未涵盖的其他角度? (注意:我不是在征求关于什么好测试的意见;我是在征求关于路由要求的路由集成测试和 Controller Action 测试之间的功能差异。)
此外,我在 Rails 4 发行说明(或 Minitest)中找不到对这种行为变化的具体引用,所以我想知道为什么首先要进行这种行为变化。我不认为这是一件坏事——我认为这是件好事——但我觉得奇怪的是没有在某个地方的更新日志中看到它。我认为 get|patch|post|delete
方法的一半要点是让您不必首先考虑路由需要哪些参数。
为了完整起见,这里是我将用于此的路由测试:
describe "CommentsController Route Integration Test" do
let(:default_options) {
{ controller: "api/v2/comments",
user_id: "1",
posts_id: "1",
format: :json }
}
it "#index" do
assert_routing "/api/v2/users/1/posts/1/comments",
default_options.merge(action: "index")
end
end
更新
我一直在寻找 ActionDispatch 代码来寻找答案……到目前为止我唯一能看到的是 url_for
自 Rails 3 以来发生了很大变化,并且 ActionController::UrlGenerationError 类本身已添加到 Rails 4 中。因此,这些新的、更严格的路由要求可能是对 ActionView 和 ActionController 解耦的附带更改。
最佳答案
我相信测试路由和 Controller 是完全没有必要的,因为您已经进行了功能测试。这并不能直接回答您的问题,但应该可以解决您的困境。我建议阅读各种测试哲学,并(进一步)形成关于如何测试和测试什么的理想观点。
关于ruby-on-rails - 仍然建议使用 Minitest 在 Rails 4 中测试路由吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937110/