名称错误: 未初始化常量 Shoulda

5

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

但是在运行第 Models 章节的 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.

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

我的测试位于spec/models目录下,看起来像这样:

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

我需要提供更多的代码吗?

1个回答

15

根据GitHub上的这个问题

您可能需要将以下内容添加到您的spec_helper.rb文件中:

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

同时,请确保在rails_helper中引用了spec_helper(在测试文件中也要引用rails_helper)。

编辑以供未来读者参考:第二行可能在最近的Rails版本中已经被弃用(请参见评论),因此不需要添加它。


1
然后我得到了以下错误:失败/错误:需要“shoulda/matchers/integrations/rspec” LoadError: 无法加载此类文件 - shoulda/matchers/integrations/rspec - kame
4
只需添加第一行,而不是第二行。 - Samuel Faure
2
只需将Shoulda :: Matchers.configure块移动到紧挨着RSpec.configure块的位置,该问题就会得到解决。 - tbem

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接