NoMethodError:在单元测试中使用Shoulda-matchers时进行测试的未定义方法“ belong_to”

时间:2020-02-13 16:06:14

标签: ruby-on-rails ruby shoulda shoulda-matchers

我试图使用shoulda-matchers来测试模型之间的关联。但是,它始终显示错误: 以Test#test_belongs_to: NoMethodError:未定义方法belong_to' for #<TakingTest:0x00007fc14b8e64a8> test/models/taking_test.rb:8:in在“ 我检查了其他答案,其中大多数是至少在4年前。它仍然可以在Rails 6.0上使用吗?

红宝石“ 2.6.5”

rails','〜> 6.0.2'

gem文件

group :development, :test do
  gem 'rspec-rails'
end
group :test do
  gem 'shoulda', '~> 3.5'
  gem 'shoulda-matchers'
end

spec / rails_helper.rb:

Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    with.test_framework :rspec
    with.library :rails
 end
end

test / models / taking_test.rb

class TakingTest < ActiveSupport::TestCase
   test "belongs to" do
     should belong_to(:students)
   end
end

1 个答案:

答案 0 :(得分:0)

同时具有spec目录和test目录可能会导致您的问题。 IMO,每个项目都应该只有spectest,而不能两个都没有。

通常,测试文件以test_helper.rb文件的包含开头。

require 'test_helper'

您有一个test_helper,而不是spec_helper

尝试将Shoulda初始值设定项从spec/spec_helper.rb移至test/test_helper.rb

相关问题