has_many :through
rspecと自己双方向の関係をテストしていて、ジョイントレコードがケースから消えてしまいます。もちろん、私はそれぞれの間でDBを掃除しているわけではありません。has_many:rspecの実行時に継承レコードが永続的でない
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
第二のテストは失敗します。ここで私は私の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
}
]
.[]
この投稿rspec testing has_many :through and after_save問題が解決しませんでした。
ここに私のspec_helper.rbです: config.before(:スイート)は、今アップフロント エンド#クリーンスイート:トランザクション DatabaseCleaner.clean_with(削除) DatabaseCleaner.strategy =を行います – jgburet
DatabaseCleanerについてすべてを削除し、ベースを落としてテストを実行しても、同じ方法で失敗します。 – jgburet
これは意味があります。問題は、データベースクリーナーではありません。 2番目のテストでは、次のような関係は決して設定されていないようです。 2回目のテストの初めに '@teen.follow @ bieber'を追加するとあなたに何が与えられますか? –