有没有比这更好/更简单的方法来测试 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
是好习惯吗?因为只是构建它会抛出一个错误(因为工厂的必填字段不会通过构建设置)。
Rails 已经测试了增量计数器。我们应该做的是在启用
belongs_to :question
的情况下测试Answer的counter_cache
关联。
RSpec.describe Answer, type: :model do
it { should belong_to(:question).counter_cache(true) }
end