I'm testing my has_many :through
-self-bidirectional relationship with rspec and my joint record simply disappear from a case to another. Of course, I'm not cleaning the db between each, only after all.
author.rb
class Author < ActiveRecord::Base
has_many :follower_relationships,
foreign_key: :follower_id,
class_name: AuthorsRelationship,
dependent: :destroy
has_many :followed_relationships,
foreign_key: :followed_id,
class_name: AuthorsRelationship,
dependent: :destroy
has_many :followers, through: :followed_relationships
has_many :followeds, through: :follower_relationships
def follow(followed)
followeds << followed
true
end
def unfollow(followed)
!!(follower_relationships.find_by_followed_id(followed).try :destroy)
end
end
authors_relationship.rb
class AuthorsRelationship < ActiveRecord::Base
belongs_to :follower, foreign_key: :follower_id, class_name: Author
belongs_to :followed, foreign_key: :followed_id, class_name: Author
validate :ensure_different_targets
validates_uniqueness_of :followed_id,
scope: :follower_id,
message: 'is already following the target'
private
def ensure_different_targets
unless follower != followed
errors.add(:follower_id, "can't be equal to followed_id")
end
end
end
author_spec.rb
RSpec.describe Author, type: :model do
describe Author, '#follow' do
before :all do
DatabaseCleaner.start
@bieber = Author.create!(name: 'Justin Bieber', screen_name: 'justinbieber')
@teen = Author.create!(name: 'Aya No', screen_name: 'Ayano2327')
end
before :each do
@bieber.reload
@bieber.followers.reload
@bieber.followeds.reload
@teen.reload
@teen.followers.reload
@teen.followeds.reload
end
after :all do
DatabaseCleaner.clean
end
context 'without followers yet' do
it 'returns true' do
result = @teen.follow @bieber
ap AuthorsRelationship.all
expect(result).to be true
end
it 'should be following after call' do
ap AuthorsRelationship.all
expect(@teen.followeds).to eq [@bieber]
end
end
end
end
Second test fails. Here's the output I got from my ap
:
[
[0] #<AuthorsRelationship:0x00000002355f00> {
:id => 15,
:follower_id => 22,
:followed_id => 21,
:created_at => Mon, 04 Apr 2016 21:25:04 UTC +00:00,
:updated_at => Mon, 04 Apr 2016 21:25:04 UTC +00:00
}
]
.[]
This post rspec testing has_many :through and after_save didn't solve the issue.