NameError: unitialized constant ServiceName with default rspec configuration

NameError: unitialized constant ServiceName with default rspec configuration

我用 rails new --api whatever 创建了:

gem 'rspec-rails', '~> 3.8'

在我的 Gemfile 中。然后,我创建了:

app/services/whatever_module/whatever_class.rb

和相应的规范文件:

spec/services/whatever_module/whatever_class_spec.rb 

现在,当我 运行:

rspec services

我收到这个错误:

NameError: uninitialized constant WhateverModule

如何让 rspec 通过规范路径识别模块?

你的规格文件应该在

spec/services/distamce/whatever_class_spec.rb.

在你的情况下 rspec 试图找到 WhateverModule 因为 /whatever_module/ 在你的规范文件路径中。您可以尝试将此更改为 spec/services/foo_bar/whatever_class_spec.rb,您将收到缺少的 FooBarModule 错误。

我想我明白你错过了什么。

Rspec 不会自动需要您的应用程序文件夹,因此应用程序文件夹最初没有模块或 类 可用。

当您检查 https://github.com/rspec/rspec-rails#installation @2 时,您可以看到您必须为 rspec 添加一些样板文件,例如 rails_helper.rbspec_helper.rb 以及 rails generate rspec:install .这些负责所有 rspec 相关设置和应用程序文件夹的要求。

还需要在每个规格文件顶部添加 require 'rails_helper'

完成所有这些操作后出现错误 Unable to autoload constant WhateverModule::WhateverClass 然后您的 whatever_class.rb 必须看起来像这样

module WhateverModule
  class WhateverClass
  end
end

或者您在 whatever_module 文件夹之外的文件中定义模块。