测试 Rails 计数器缓存的更好方法?

问题描述 投票:0回答:1

有没有比这更好/更简单的方法来测试 RSpec 中的 Rails 计数器缓存:

let(:question) { create(:question) }

it "has a counter cache" do
  expect {
    create(:answer, question_id: question.id, user_id: question.user.id)
  }.to change {
    question.reload.answers_count
   }.by(1)
end

此外,在这里的工厂使用

#create
而不是
#build
是好习惯吗?因为只是构建它会抛出一个错误(因为工厂的必填字段不会通过构建设置)。

ruby-on-rails ruby-on-rails-3 rspec ruby-on-rails-4
1个回答
0
投票

Rails 已经测试了增量计数器。我们应该做的是在启用

belongs_to :question
的情况下测试Answer的
counter_cache
关联。

RSpec.describe Answer, type: :model do
  it { should belong_to(:question).counter_cache(true) }
end
© www.soinside.com 2019 - 2024. All rights reserved.