路径辅助方法并非在所有 RSpec 个文件中可用

Path helper methods not available in all RSpec files

我大致遵循 Rails Tutorial by Michael Hartl,现在我正在尝试设置一些 RSpec 测试。这是我的 routes.rb

Rails.application.routes.draw do
  root 'static_pages#home'
  get  '/help',    to: 'static_pages#help'
  get  '/about',   to: 'static_pages#about'
  get  '/contact', to: 'static_pages#contact'
  get  '/signup',  to: 'users#new'
end

我有一个 spec/integration/site_layout_spec.rb 文件,我可以在其中使用辅助方法,例如 signup_path:

# site_layout_spec.rb

require 'rails_helper'

RSpec.describe 'Root' do
  it 'shows the home page' do
    get signup_path # just to show it's working
    get root_path
    expect(root_path).to render_template('static_pages/home')
  end
end

我还有一个文件spec/controllers/users_controller_spec.rb。在此文件中,*_path 辅助方法中的 none 似乎有效。

# user_controller_spec.rb

require 'rails_helper'

RSpec.describe 'User signup page' do
  it 'should be available' do
    get signup_path
    expect(signup_path).to exist
  end
end

当运行rspec时,我得到

Failure/Error: get signup_path
NoMethodError: undefined method `signup_path' for nil:NilClass
# ./spec/controllers/users_controller_spec.rb:5:in `block (2 levels) in <main>'

为什么助手在我的第二次测试中不起作用?

后者是一个控制器规范,您需要在没有路由的情况下通过调用它的操作来测试控制器:

get :new