【问题标题】:Strange Behaviour of Counter Cache In Spec规范中计数器缓存的奇怪行为
【发布时间】:2014-07-02 16:13:34
【问题描述】:

我在 Gallery 上设置了一个标准计数器缓存来跟踪其照片。计数器缓存按照 Rails 默认命名为 photos_count

在我的图库规范中,我像这样测试计数器缓存:

  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

这有效,但仅适用于对 gallery.reload 的调用。为什么这个规范没有调用reload 就失败了。每次失败都是因为photos_count没有变化。

注意with_photos_count 是工厂使用的瞬态属性。

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-4 rspec counter-cache


    【解决方案1】:

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

    仅在测试环境中需要。

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

    【讨论】:

    • 是的,我已经阅读了这个问题,但是在他的回答的第二部分中没有使用reload
    • 不同之处在于,在另一个示例中,计数是通过User.last.media_count 检索的,这会强制执行另一个查询。您的示例测试了 gallery 实例中的缓存值。
    猜你喜欢
    • 2018-05-29
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2021-06-10
    • 2012-03-17
    • 2019-07-19
    相关资源
    最近更新 更多