我遇到了问题counter_cache
。假设我有三个模型。User 和 Article 有很多 ArticleUpvotes。用户可以为文章创建 ArticleUpvote。
用户
# models/user.rb
class User < ActiveRecord::Base
has_many :upvotes, class_name: 'ArticleUpvote'
def upvote(article)
article.upvotes.create(user: self)
end
end
文章
# models/article.rb
class Article < ActiveRecord::Base
has_many :upvotes, class_name: 'ArticleUpvote'
end
文章支持
# models/article_upvote.rb
class ArticleUpvote < ActiveRecord::Base
include ArticleVote
belongs_to :article, dependent: :destroy, counter_cache: :upvotes_count
end
# models/concerns/article_vote
module ArticleVote
extend ActiveSupport::Concern
included do
belongs_to :user
validates :user, presence: true
end
end
失败的测试
context 'voting' do
let(:user) { FactoryGirl.create(:user) }
let(:article) { FactoryGirl.create(:article) }
context '#upvote' do
it 'adds upvote to article' do
user.upvote(article)
expect(article.upvotes.size).to eq 1
end
end
end
错误
1) User voting #upvote adds upvote to article
Failure/Error: expect(article.upvotes.size).to eq 1
expected: 1
got: 0
(compared using ==)
通过测试
只需将我的测试机构更改为:
user.upvote(article)
article.upvotes.size # Added this line compared to failing version
expect(article.upvotes.size).to eq 1
或者这样做:
expect{ user.upvote(article) }.to change{ article.upvotes.size }.by 1
使测试通过。为什么会这样?