Rails 路由测试

Rails routes testing

我是测试新手,我有一个问题。

此代码测试该路线是否正确,好吗?

test "root should route to home#index" do
assert_routing "/", {controller: "home", action: "index"}
end

如何测试相反的情况?我有

resources :sessions, :only=>[:new, :create, :destroy]

在我的路线中。我如何测试您无法进入会话#edit?

难道我不应该测试它吗?

编辑:我忘了说了,我使用的是默认工具。

如果您正在使用 RSpec,您可以

it "does not route to sessions/edit" do
  expect(:get => "/sessions/edit").not_to be_routable
end

有关编写路由规范的更多信息,请参阅https://relishapp.com/rspec/rspec-rails/docs/routing-specs/be-routable-matcher

你可以试试这个,它会失败,除非测试 assert_generates 引发一个 "UrlGenerationError" => 无法为会话生成 url#edit

test "route should not exist" do
  begin
    assert_generates "sessions/edit", controller: :sessions, action: :edit
    flunk "Route to should not exist"
  rescue ActionController::UrlGenerationError
  end
end