Search code examples
ruby-on-railsrubyminitest

Rails minitest failed in has_many validation


I've got simple belongs_to/has_many relation like below:

class AppropriatenessTestResult < ApplicationRecord
  belongs_to :appropriateness_test_question
end

class AppropriatenessTestQuestion < ApplicationRecord
  has_many :appropriateness_test_results, dependent: :destroy
end

migration for AppropriatenessTestResult:

class CreateAppropriatenessTestResults < ActiveRecord::Migration[6.1]
  def change
    create_table :appropriateness_test_results do |t|
      t.references :appropriateness_test_question, foreign_key: true, index: { name: 'idx_appropriateness_test_question_id' }

      t.timestamps
    end
  end
end

Now I want to test if relations are set properly. To do so I wrote Minitest for AppropriatenessTestQuestion model:

require 'test_helper'

class AppropriatenessTestQuestionTest < ActiveSupport::TestCase
  context 'associations' do
    should have_many(:appropriateness_test_question)
  end
end

which gives me an error:

Failure: AppropriatenessTestQuestionTest#test_: associations should have many appropriateness_test_question. Expected AppropriatenessTestQuestion to have a has_many association called appropriateness_test_question (no association called appropriateness_test_question)

What did I missed?


Solution

  • Fixed it! I accidentally checked associations of appropriateness_test_questions instead of appropriateness_test_results

    should be:

    should have_many(:appropriateness_test_results)
    

    instead of:

    should have_many(:appropriateness_test_questions)