NoMethodError: undefined method `setup' for RSpec::ExampleGroups::ApplicationsController:Class

NoMethodError: undefined method `setup' for RSpec::ExampleGroups::ApplicationsController:Class

搜索此问题只发现了其他人处理过的特定宝石或 类 的问题。就我而言,我认为 rspec 通常有问题。

每当我用 rails generate ControllerName 生成一个控制器时,它都会设置好一切,而且一切似乎都运行良好。我已经路由了几个控制器并在开发和生产中测试了它们,一切正常。

唯一似乎有问题的是用 rspec 测试它们。现在我的项目中有两个控制器,每当我 运行 rspec/spec 时,rails g 生成的大多数规范都会出现此错误:

NoMethodError:
  undefined method `setup' for RSpec::ExampleGroups::MoreStuffHere

例如,我有一个 WelcomeController 和 ApplicationsController,这些是我不断收到的错误:

undefined method `setup' for RSpec::ExampleGroups::ApplicationsController:Class
undefined method `setup' for RSpec::ExampleGroups::WelcomeController:Class
undefined method `setup' for RSpec::ExampleGroups::WelcomeAboutHtmlErb:Class
undefined method `setup' for RSpec::ExampleGroups::WelcomeIndexHtmlErb:Class

有趣的是,我没有收到他们 helper_spec

的错误

如果这有帮助,这里是一个完整的错误:

An error occurred while loading ./spec/controllers/applications_controller_spec.rb.

Failure/Error:
  RSpec.describe ApplicationsController, type: :controller do

  end

NoMethodError:
  undefined method `setup' for RSpec::ExampleGroups::ApplicationsController:Class
# ./spec/controllers/applications_controller_spec.rb:3:in `<top (required)>'

有人知道这个问题出在哪里吗?

spec_helper.rb我有

require File.expand_path("../../config/environment", __FILE__)
require 'rails/all'

RSpec.configure do |config|
  # More code here.
end

我所要做的就是在 require 'rails/all' 下添加 require 'rspec/rails'。这解决了我的问题。

但是,我不知道为什么。如果有人可以详细说明那会很棒。我在 rails_herlper.rb 中已经有 require 'rspec/rails',但显然这还不够好。

恕我直言,这里的解决方案有点像 Damian Rivas 在那里所说的,但重要的是:

  • 在rails helper 你有一行:

require 'spec_helper'

  • 在 spec_helper 中,您在配置块行中包含设计助手:

config.include Devise::Test::ControllerHelpers, type: :controller

  • 你也如上所述必须有rspec/rails要求行

这里的要点是你必须注意这里的顺序...总是包括 rspec/rails 必须在 spec_helper

之前

所以假设示例 spec_helper.rb 看起来像:

require 'rubygems'

Rspec.configure do |config|
  config.include Devise::Test::ControllerHelpers, type: :controller
end

然后我们的 rails_hepler.rb 必须看起来像:

ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort('The Rails environment is running in production mode!') if Rails.env.production?

require 'rspec/rails'
require 'spec_helper'

然后在 sample_spec.rb 中你需要 rails_helper,或者在我的情况下我需要通过 .rspec 所以我不必把它放在每个规范的顶部。

希望对大家有所帮助:)