I get got errors: User must exist in the unit model test

What to do when you get got errors: User must exist in the unit model test

ruby '2.6.5' rails '6.0.0'

medicine_spec.rb


before do
    @medicine = FactoryBot.build(:medicine)
    @medicine.image = fixture_file_upload('public/images/money.jpg')
  end
  describe 'New registration of medicine' do
    context 'When new drug registration is successful' do
      it "medicine,symptom,date,You can register if the image exists" do
        expect(@medicine).to be_valid
      end
    end

This test code gives the following error.

5.png

I made a hypothesis. Since I got got errors: User must exist, I hypothesized that user information is related.

medicine.rb


   class Medicine < ApplicationRecord
     has_one_attached :image
     belongs_to :user
     with_options presence: true do
       validates :medicine
       validates :symptom
       validates :date
     end
   end

user.rb


    has_many :medicines

The model association is assembled. The next thing I thought about was hypothesis that the association was not formed at the time of the test to enter the value.

medicines.rb


   FactoryBot.define do
     factory :medicine do
        medicine { 'Loxonin' }
        symptom { 'Cold' }
        date { Time.now.utc }
       user
     end
   end
   

Added ʻassociation: user`. I will test it.

6.png

I passed the test safely!

I will pass the test without fail, but if an error occurs, I can check the connection of the application, so I will continue learning! 6.png

Recommended Posts

I get got errors: User must exist in the unit model test
[Rails] Unit test code for User model
I want to get the value in Ruby
I get Mysql2 :: Error :: ConnectionError in the production environment
Get the name of the test case in the JUnit test class
What I stumbled upon in the ActiveModel :: Serializer test
I got stuck in File
Problem that the attribute of User model becomes nil in ActionMailer
Password dummy data generation notes in Rails model unit test code
[Android] I want to get the listener from the button in ListView