【问题标题】:NameError: uninitialized constant ShouldaNameError:未初始化的常量应该
【发布时间】:2021-04-30 01:06:50
【问题描述】:

我做这个教程 https://www.digitalocean.com/community/tutorials/build-a-restful-json-api-with-rails-5-part-one

但是在模型章节运行 RSpec 测试时,我收到以下错误。

C:\Users\NCH-Lap10\Desktop\rubyprojects\todos-api>bundle exec rspec

An error occurred while loading ./spec/controllers/items_controller_spec.rb.
Failure/Error:
  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end

NameError:
  uninitialized constant Shoulda
# ./spec/rails_helper.rb:6:in `<top (required)>'
# ./spec/controllers/items_controller_spec.rb:1:in `require'
# ./spec/controllers/items_controller_spec.rb:1:in `<top (required)>'

An error occurred while loading ./spec/controllers/todos_controller_spec.rb.
Failure/Error:
  Shoulda::Matchers.configure do |config|
    config.integrate do |with|
      with.test_framework :rspec
      with.library :rails
    end
  end

NameError:
  uninitialized constant Shoulda
# ./spec/rails_helper.rb:6:in `<top (required)>'
# ./spec/controllers/todos_controller_spec.rb:1:in `require'
# ./spec/controllers/todos_controller_spec.rb:1:in `<top (required)>'

An error occurred while loading ./spec/models/item_spec.rb.

所以他没有找到我的测试。 (我从教程中复制了它们)

我的测试位于规格/模型中,看起来像:

require 'rails_helper'

# Test suite for the Item model
RSpec.describe Item, type: :model do
  # Association test
  # ensure an item record belongs to a single todo record
  it { should belong_to(:todo) }
  # Validation test
  # ensure column name is present before saving
  it { should validate_presence_of(:name) }
end

我的 Gemfile 的一部分:

group :test do
  gem 'factory_bot_rails', '~> 4.0'
  gem 'shoulda-matchers', '~> 3.1'
  gem 'faker'
  gem 'database_cleaner'
end

我应该提供更多代码吗?

【问题讨论】:

    标签: ruby-on-rails ruby rspec ruby-on-rails-5


    【解决方案1】:

    根据this issue on github

    您可能希望将此添加到您的spec_helper.rb

    require "shoulda/matchers"
    require "shoulda/matchers/integrations/rspec"
    

    另外,请确保 rails_helper 中需要 spec_helper(并且您的测试文件中需要 rails_helper)。

    为未来的读者编辑:最近的 Rails 版本中可能不推荐使用第二行(请参阅 cmets),所以不要添加它

    【讨论】:

    • 然后我收到以下错误:Failure/Error: require "should/matchers/integrations/rspec" LoadError: cannot load such file -- shoulda/matchers/integrations/rspec
    • 只添加第一行而不是第二行
    • 只需将块 Shoulda::Matchers.configure 移动到 RSpec.configure 块旁边即可解决该问题。
    猜你喜欢
    • 1970-01-01
    • 2015-01-19
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2016-06-12
    • 2015-03-01
    相关资源
    最近更新 更多