NoMethodError: undefined method `belong_to' for test when using shoulda-matchers in unit test

811 views Asked by At

I tried to use shoulda-matchers to test the association between models. However, it always show Error: TakingTest#test_belongs_to: NoMethodError: undefined method belong_to' for #<TakingTest:0x00007fc14b8e64a8> test/models/taking_test.rb:8:inblock in ' I checked other answer, most of them are at least 4 years ago. Does it still work with rails 6.0?

ruby '2.6.5'

rails', '~> 6.0.2'

gem file

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

There are 1 answers

0
Aaron Breckenridge On

Having both a spec directory and a test directory could be causing your problem. IMO, there should only ever be spec or test for a every project, never both.

Usually, test files begin with an include for the test_helper.rb file.

require 'test_helper'

Instead of a test_helper, you've got a spec_helper.

Try moving the Shoulda initializer from spec/spec_helper.rb to test/test_helper.rb