Home>
I want to achieve

I am writing a test to see if the child model associated with the parent model is deleted when the parent model is deleted in the RSpec test.

The one-to-many test passes successfully, but the many-to-many test doesn't work.
When I try it on the console, it is deleted properly, but the test does not pass.

If i understand, I would like you to lend me your wisdom.
Thank you m (_ _) m

error
expected `Relationship.count` to have changed by -1, but was changed by 0

user_rspec.rb

require'rails_helper'
RSpec.describe User, type:: model do
let (: user) {FactoryBot.create (: user)}
let (: other_user) {FactoryBot.create (: user, email: "[email protected]", name: "Tanaka")}
describe'related table delete test' do
 it'Delete user deletes user's post' do
     user.posts.create (content: "RSpec")
     expect {user.destroy} .to change {Post.count} .by (-1)
 end
 it'Delete user removes user's habit' do
     user.habits.create (task: "muscle training", frequency: 3)
     expect {user.destroy} .to change {Habit.count} .by (-1)
 end
 it'Delete user deletes user's record' do
     user.records.create (level: 10, date: Date.current)
     expect {user.destroy} .to change {Record.count} .by (-1)
 end
  #Test that causes an error ↓
 it'Delete user removes relationships associated with user' do
     user.active_relationships.create (followed_id: other_user)
     expect {user.destroy} .to change {Relationship.count} .by (-1)
 end
end
end

user.rb

class User
version

Rails 6.0.3.4
ruby 2.6.3p62
RSpec 3.10

  • Answer # 1

    Not user.active_relationships.create (followed_id: other_user)
    It was solved by setting user.active_relationships.create (followed_id: other_user.id).