ChatGPT解决这个技术问题 Extra ChatGPT

Rspec 没有看到我的模型类。未初始化的常量错误

我正在为我在 Ruby on Rails 应用程序中的模型编写 Rspec 测试。我在启动 'rspec spec' 时收到此错误

command:
/spec/models/client_spec.rb:4:in `<top (required)>': uninitialized constant Client (NameError)

我使用 Rails 4.0.0 和 Ruby 2.0.0

这是我的client_spec.rb:

require 'spec_helper'


describe Client do

  it 'is invalid without first_name', :focus => true do
     client = Client.new
     client.should_not be_valid
  end
end

和 Gemfile:

source 'https://rubygems.org'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.rc1'

# Use sqlite3 as the database for Active Record
gem 'sqlite3'

# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc1'

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'

# gem 'therubyracer', platforms: :ruby

# Use jquery as the JavaScript library
gem 'jquery-rails'

# Turbolinks makes following links in your web application faster. Read more: 
gem 'turbolinks'

gem 'jbuilder', '~> 1.0.1'

group :development do
  gem 'rspec-rails'
end

group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

group :test do
  gem 'rspec-rails'
  gem 'factory_girl_rails'
  gem 'database_cleaner'
end

最后是 client.rb(ROR 模型和类):

class Client < ActiveRecord::Base

  has_many :cars
  has_many :orders
  has_one :client_status
  has_one :discount_plan, through: :client_status

  validates :email, format: { with: /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})\z/, :message => "Only emails allowed", :multiline => true }
  validates :email, presence: true, if: "phone.nil?"
  #validates :phone, presence: true, if: "email.nil?"
  validates :last_name, :first_name, presence: true
  validates :last_name, :first_name, length: {
      minimum: 2,
      maximum: 500,
      wrong_length: "Invalid length",
      too_long: "%{count} characters is the maximum allowed",
      too_short: "must have at least %{count} characters"
     }
end

如果它对我的 spec_helper.rb 文件有用:

# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  #config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

   config.before(:each) do
     DatabaseCleaner.start
   end

   config.after(:each) do
     DatabaseCleaner.clean
   end

  end
对我有用的是从 .rspec 中删除行 --require spec_helper。因为它已经包含在 spec_helper 之后加载的 --require rails_helper

s
stevec

在 rails 4.x 及更高版本(rspec-rails 3.1.0 及更高版本)中,将其添加到每个规范文件的顶部:

require "rails_helper"  # this

不是

require "spec_helper"   # not this

出于谷歌搜索的目的,这应该是它自己的问题;我一直在与我认为是坏掉的 Capybara、坏掉的发射器或坏掉的东西(填充宝石)作斗争,这一切都是由于这一行的改变。
需要“rails_helper”在 rails 3.2.22 (rspec-rails 3.2.1) 上工作
这非常令人困惑。我正在构建一个新的 Rails 6 应用程序并运行我的第一个规范。它肯定是在加载 rails_helper.rb 文件,但我现在看到它在尝试运行规范后尝试加载它。将 require "rails_helper" 添加到我的规范顶部,我很高兴。
E
Erik Escobedo

您的 spec_helper 文件缺少一些重要命令。具体来说,它不包括配置/环境和初始化 rspec-rails

您可以将以下行添加到 spec/spec_helper.rb 文件的开头

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'

或者你可以运行

rails generate rspec:install

并用生成的用于 rspec-rails 的内容覆盖您的 spec_helper


较新版本的 RSpec 将一些内容从 spec/spec_helper.rb 文件中移出,因此现在您还获得了一个 spec/rails_helper.rb 文件。如果您运行 rails generate rspec:installthis is what it produces(rspec-rails 3.0.1,rails 4.1.1)。原来 rails_helper.rb 文件包含一些与您的代码相似的代码,当您想在规范中加载 Rails 时应该需要。
丹尼斯走在正确的轨道上。我相信将要测试 Rails 功能的测试配置应该从 spec_helper.rb 移到 rails_helper.rb。此外,请务必阅读 rails_helper.rb 中提到 rspec-rails 如何infer_spec_type_from_file_location 的注释,这可能会使您将规范测试重新定位到不同的 spec/*/ 子目录中。
如果您想自动包含 spec/rails_helper.rb,您可以在 .rspec 中添加 --require rails_helper
但是将 --require rails_helper 添加到 .rspec 并没有破坏分离两个助手的点。我认为您将始终加载 rails_helper(因此也是 Rails),即使对于不需要 Rails 的规范也是如此。
这有很大帮助。我实际上需要将我的 .travis.yml 更新为 bin/rspec
U
Umang Raghuvanshi

您可能还想在 .rspec 文件中添加 --require rails_helper,使其看起来像这样。

--color
--require spec_helper
--require rails_helper

在此之后,您不需要在所有规范中都需要 rails_helper 。


如果您需要为每个测试加载 Rails 环境,这很好,但如果不是,这最终会导致您的测试套件比它需要的速度慢,正如一些人在上面另一个答案的评论中提到的那样。
K
Kent Aguilar

我正在使用 Rails 5.0.0.1。以下是我解决这个问题的方法。

在您的 Gemfile 中,请添加 -> gem 'rspec-rails', ">= 2.0.0.beta"

像这样,

group :development, :test do
  gem 'rspec-rails', ">= 2.0.0.beta"
end

原因:如果没有添加rspec-rails,执行rspec命令时会产生这个错误->“cannot load such file -- rails_helper”

现在,在终端上执行此命令。

捆绑安装

一旦 bundle 命令运行良好,执行 rails generate。像这样,

rails 生成 rspec:install

原因:此命令将创建一个新的 .rspec(提示时覆盖),spec/rails_helper.rb 和 spec/spec_helper.rb

现在,在这一点上,rspec 应该几乎可以正常运行。但是,如果您遇到在模型中找不到的错误,例如无法加载此类文件 - 想法,请尝试将其添加到您的 spec/spec_helper.rb

require 'rubygems'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)

原因:似乎 spec_helper 没有加载 Rails 环境。我们需要它。

希望这可以帮助!


L
Longfei Wu

如果此问题下的其他答案不起作用,请尝试:

检查文件名或类名中是否有任何拼写错误(它们应该匹配)

否则,

检查你的 config/environment/test.rb 文件,看看是否有 config.eager_load = false,设置为 true。

您应该检查书面订单,因为您不想解决拼写错误的问题。


config.eager_load 设置为 true 为我解决了这个问题。谢谢!
请注意,如果您需要 spec_helper,则 test.rb 中有此注释:# If you are using a tool that preloads Rails for running tests, you may have to set it to true.
L
L.Youl

上面的答案都没有让我很满意,或者对需要放置代码行的位置不够明确。我正在使用 rails 6.0.2 和 rspec-rails 4.1.0 并找到了两个解决问题的选项。

将行 require 'rails_helper' 添加到您需要运行的每个规范文件的顶部。将行 require 'rails_helper' 添加到 spec/spec_helper.rb 文件的顶部,以使 rails 帮助文件在所有测试中都可用。


A
Arnaud Bouchot

自从创建此线程以来,事情发生了一些变化,我在使用 Ruby 2.1、Rails 4.2、rspec-rails 3.3 时也遇到了 uninitialized constant ClassName (NameError) 错误。

我已经解决了阅读 rspec-rails gem 文档的问题:

https://github.com/rspec/rspec-rails#model-specs

它证实了 Swards 关于不再需要“rails_helper”而不是“spec_helper”的说法。

此外,我的模型规范看起来更像是 gem docs 中的规范

RSpec.describe Url, :type => :model do
    it 'is invalid without first_name', :focus => true do
        client = Client.new
        client.should_not be_valid
    end
end

b
bluray

在您的应用程序中定义的工厂文件夹

FactoryBot.define do
  factory :user_params , :class => 'User' do
    username 'Alagesan'
    password '$1234@..'

  end
end

您的控制器 RSpec 文件:

it 'valid params' do
  post :register, params: {:user => user_params } 
end

关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅