GETting root_path 时没有路由错误,但仅在我的一些测试中

No route error when GETting root_path, but only in some of my tests

我在routes.rb中定义了一个root_path,我在其他测试中调用了get root_path,但是由于某些原因,在test/controllers/application_controller_test.rb中,我在调用时出现了这个错误get root_path:

ApplicationControllerTest#test_should_get_index_when_not_logged_in:
ActionController::UrlGenerationError: No route matches {:action=>"/", :controller=>"application"}
test/controllers/application_controller_test.rb:10:in `block in <class:ApplicationControllerTest>'

这里是routes.rb

Rails.application.routes.draw do
  root               'application#index'
  get    'signup' => 'users#new'
  get    'login'  => 'sessions#new'
  post   'login'  => 'sessions#create'
  delete 'logout' => 'sessions#destroy'

  resources :users
  resources :account_activations,  only: [:edit]
  resources :password_resets,      only: [:edit, :new, :create, :update]
  resources :lessons,              only: [:show, :index] do
    resources :pre_lesson_surveys, shallow: true,
                                   except:  :destroy
  end
end

这里是application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper

  def index
    render 'admin_home_page' if admin?
    render 'user_home_page'  if logged_in?
    @user = User.new         unless logged_in?
  end
end

这是 tests

之一
test "should get index when not logged in" do
  get root_path
  assert_response :success
  assert_not is_logged_in?
  assert_template 'application/index'
end

我确定我只是在做一些愚蠢的事情,但我不能指责它

如果您想确保 index 模板在对根路径的请求中呈现,请求规范可能是合适的:

spec/requests/application_requests_spec.rb:

describe "Test Root Path" do
  it 'successfully renders the index template on GET /' do
    get "/"
    expect(response).to be_successful
    expect(response).to render_template(:index)
  end
end

如果您想确保 index 模板根据对 ApplicationController 的索引操作的请求呈现,控制器规范可能是合适的。

spec/controllers/application_controller_spec.rb:

describe ApplicationController do
  describe "GET index" do
    it "successfully renders the index template" do
      expect(controller).to receive(:index)
      get :index
      expect(response).to be_successful
      expect(response).to render_template(:index)
    end
  end
end