I have a standard counter cache set up on Gallery to track its Photos. The counter cache is named as per Rails default photos_count
.
In my Gallery spec I test the counter cache like this:
it "updates 'photos_count' counter cache" do
gallery = create(:gallery_with_photos, with_photos_count: 3)
gallery.reload # Fails without this
expect(gallery.photos_count).to eq 3
expect {
gallery.photos.first.destroy
gallery.reload # Fails without this
}.to change{ gallery.photos_count }.by(-1)
gallery.photos << create(:photo)
expect {
gallery.save!
gallery.reload # Fails without this
}.to change { gallery.photos_count }.by(1)
end
This works, but only with the calls to gallery.reload
. Why does this spec fail without the calls to reload
. Each failure is because there is no change in photos_count
.
Note with_photos_count
is a transient attribute used by the factory.