0

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.

4

1 回答 1

3

发生这种情况是因为计数器更新是在查询之后执行的,您需要从数据库中重新获取对象才能看到效果。

它仅在测试环境中需要。

这里也已经对此进行了讨论: Rspec testing of counter_cache column's returned 0

于 2014-07-02T16:23:39.417 回答